Implement cross-browser html5 Form Verification and cross-browser html5 form

Source: Internet
Author: User

Implement cross-browser html5 Form Verification and cross-browser html5 form

Many types of forms are added to html5 forms, and the verification function is also provided. On mobile devices, mobile phones, and other devices, different types of keyboards can be displayed based on different input types, such as the iphone keyboard.

<Input type = "email">

<Input type = "number">

<Input type = "tel">

Iphone can play different types of keyboards for easy input

However, because different browsers have different styles and are incompatible with the old browsers (IE9 and below), it is rare in the production environment. For example, to check the mailbox format, the effects of different browsers are as follows:

Chrome

Firefox

IE

Safari

Html5 forms have a big problem in cross-browser

Specifically, there are three problems:

(1) The check is not triggered when the input box is blur and is only triggered when the vertex is submitted. However, it is generally hoped that the user will check the input once the user leaves the input box.

(2) The UI of the prompt control is very different. safari will not trigger the prompt control. Some browsers such as IE will add a red border to the illegal input box.

(3) The text is completely written, and the text in different browsers is inconsistent. It is best to use the prompt of Chrome

I. cross-browser Form Verification plug-in

To solve these problems, there are some plug-ins on the Internet, such as html5 Form, which are processed across browsers, but the effect is not very satisfactory, and html5 Form becomes invalid under safari. In the absence of multi-party searches and attempts, I wrote a cross-browser form detection plug-in. The results are as follows:

Chrome

Firefox

IE

Safari

Example of plug-in effect: solve cross-browser Problems

1. Unified UI

This plug-in solves the above problem. First, it unifies the UI and simulates the Chrome prompt effect. The UI style and display position are consistent and can be customized. The option of whether to use the default text in the browser is provided for the text, because some browsers such as Chrome prompt are intelligent, such as the mailbox text above, if not used, the custom text.

2. support asynchronous Verification

Another powerful function is to support asynchronous verification, such as verifying whether the user name exists:

The plug-in supports asynchronous verification.

3. Support for multi-type rule verification

In addition, different types of rule verification are supported, such as required/format/custom. For example, there are two requirements for phone number verification. One is required, the other is in line with the phone number format:

Verification of different rule types is supported.

4. Switch between Chinese and English

The problem of switching between Chinese and English on Bilingual sites is also taken into account:

Switch between Chinese and English

Ii. How to Use plug-ins 1. Simplest use

The plug-in has been uploaded to github and contains a demo. The demo effect is as follows:

1 <form class = "sign-up"> 2 <label> email address </label> 3 <input type = "email" name = "account" t = "email" required = ""> 4 <label> password </label> 5 <input type = "password" name = "password" pattern = ". {6, 20} "pm =" the password must be between 6 and 20 characters "required =" "> 6 <label> confirm the password </label> 7 <input type =" password "name = "confirm-pwd"> 8 <input id = "confirm-sign" type = "submit" value = "register"> 9 <p> </p> 10 </form>

In the first row above, the type = "email" of input is defined, and another t = "email" is written mainly because browsers below IE10 will forcibly change the unknown type to text.

Unrelated CSS omitted. With the above html structure, you only need to initialize the plug-in.

New Form ($ (". sign-up ") [0], {errorMsgClass:" error ", // Class Name of the error prompt box, used to customize the style errorInputClass:" invalid ", // The input class name is invalid for customizing the style}, submit); function submit () {console. log ("Form Verification Successful, prepare to submit"); // submit operation}

When new From is executed, three parameters are passed. The first parameter is the form DOM element, the second parameter is some configuration of the verification rule, and the third parameter is the callback function that verifies the success. Corresponding:

var Form = function(form, checkOpt, submitCallback){       //...}

The second parameter checkOpt has two attributes: errorMsgClass and errorInputClass.

The simplest initialization can implement the required attribute, pattern attribute, and type validation. The regular expression is used for pattern. The error message is placed in the pm attribute. The above pm = "password must be between 6 and 20 characters ".

2. Add a custom check

The above password must be consistent with the two inputs. add custom verification in checkOpt:

CheckOpt. rule = {"confirm-pwd": {check: checkPwdIdentity, // UDF msg: "inconsistent Password Input" // error message} function checkPwdIdentity () {if (this. form ["password"]. value! = This. form ["confirm-pwd"]. value) {return false;} return true ;}

As shown above, a rule attribute is added. The key value is the name attribute of input. The value contains a custom validation function and error information.

3. Custom asynchronous check

Some data needs to be checked by the Service, such as checking whether the account exists.

CheckOpt. rule. account = {check: checkAccountExist, msg: "The account already exists! ", Async: true // flag, indicating asynchronous check}; function checkAccountExist (failCallback, successCallback) {var input = this; util. ajax ("/register/hasUser", {account: this. value}, function (data) {// if the user exists, call failCallback to add an error prompt if (data. isUser === true) {failCallback () ;}// call the successful callback function else {successCallback ();}});}

Input two parameters in the callback function. If the verification fails, run the first parameter. If the verification succeeds, run the second parameter, which is used by the plug-in.

4. error message for adding custom types

Form already provides a set of default type error prompts:

Form. prototype. validationMessage_cn = {email: 'invalid email format', number: 'invalid number format', url: 'invalid url format', password: 'invalid format', text: 'invalid format '};

You can also customize one. Replace the text above. No parameters are provided for the moment.

In addition, you can cancel the text provided by the browser and use the following default text.

// If the browser language is not Chinese, do not use English text. checkOpt. disableBrowserMsg = is applicable to bilingual sites! (Navigator. language | navigator. userLanguage). match (/cn/I)

You can also specify the language used by the Form:

// CheckOpt. lang = "cn"; // or en

 

Iii. Plug-in source code parsing

The code of the plug-in is not very complex, but many details need to be considered.

1. Add the checkValidity function to a non-html5 Browser

If there is no checkValidity function, add one to it. For the core code, see Github, which is not described here.

Var input = document. createElement ("input"); if (! Input. checkValidity) {HTMLInputElement. prototype. checkValidity = function () {// For detailed code, see github }}

 

2. add error message

The key is to calculate the position where the prompt is displayed,

Form.prototype.addErrorMsg = function(input, msg){}

 

3. Implementation of asynchronous Test

The difficulty of asynchronous check is when to execute the submit callback. The solution is to add a hasCheck attribute for each input. If the check is successful, it is set to true. Once the focus is set to false, and blur triggers the check. The submit callback can be executed only when hasCheck is true for all inputs. The second parameter of the following checkAsync is set to true when the vertex is submitted, while false when the blur is verified.

1 Form. prototype. checkAsync = function (input, doesSubmit) {2 name = input. name; 3 var rule = input. form. form. checkOpt. rule; 4 rule [name] ["check"]. call (input, 5 // callback function 6 function () {7 var Form = input. form. form; 8 Form. addErrorMsg (input, Form. checkOpt. rule [name]. msg); 9}, 10 // check the successful callback function 11 function () {12 input. hasCheck = true; 13 if (doesSubmit) {14 input. form. form. tryCallSubmit (input); 15} 16}); 17 };

Line 3 of the Code checks whether all input except submit is hasCheck and true. If yes, run the submit callback command.

Currently, this Form plug-in only supports text/password/url/email/number input, which can meet most of the Form submission requirements.

 

Refer:

1. Making HTML5 Form backwards compatible

2. Building HTML5 Form Validation Bubble Replacements

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.