Implement cross-browser HTML5 form validation

Source: Internet
Author: User

The HTML5 form adds many types of forms, and also comes with a validation feature. On the mobile side, devices such as mobile phones can eject different keyboards based on different input types, such as the iphone's keyboard

<input type= "Mail" >

<input type= "Number" >

<input type= "Tel" >

iphone bullets different types of keyboards for easy input

However, due to different browsers on the non-input prompt copy inconsistent, style is not the same, and the old browser is incompatible (IE9 and below), resulting in the production environment is relatively rare to. For example, for the verification of mailbox formats, the effects of different browsers are as follows:

Chrome

Firefox

Ie

Safari

HTML5 the form of a cross-browser has a big problem

In particular, there are three questions:

(1) input box blur will not trigger the check, only when the point of the submission of the trigger, but it is generally hoped that the user once left the input box to check its input

(2) Tip the UI of the control is very different, Safari does not trigger the prompt control, and some browsers such as IE will add a red border to the illegal input box

(3) Copy is written dead, and different browser copy inconsistent, which should be the best hint of chrome

One, cross-browser form validation plug-in

To solve these problems, there are some plug-ins online, such as HTML5 form, do cross-browser processing, but the effect is not very satisfying, HTML5 Form in Safari under the expiration. In the multi-party search and attempt, the author has written a cross-browser form detection plug-in, the effect is as follows:

Chrome

Firefox

Ie

Safari

Plug-In effect example: Troubleshoot cross-browser issues

1. Unified UI

This plugin solves the problem above, the first is to unify the UI, simulates the chrome effect, the UI style and display location are consistent, and can be customized. The option to use the default copy of the browser is provided for the copy question, because some browsers, such as Chrome, are more intelligent, such as the above mailbox copy, if not used, the custom copy.

2. Support Asynchronous authentication

Another powerful feature is the ability to support asynchronous authentication, such as verifying that a user name exists:

Plug-in supports asynchronous validation

3. Support multi-type rule validation

Also, support for different types of rule validation, such as mandatory/format/custom, such as two requirements for verification of phone numbers, one is required, and the other is in the format of the phone number:

Support for validation of different rule types

4. Ability to switch between Chinese and English

Also take into account the bilingual station in the English switching problem:

Support Chinese and English switching

Second, plug-in use Method 1. The simplest to use

The plugin has been uploaded to GitHub, which contains a demo,demo effect as follows:

HTML structure of the form:

1     <formclass= "Sign-up">2         <label>Email address</label>3         <inputtype= "Email"name= "Account"T= "Email"Required="">4         <label>Password</label>5         <inputtype= "Password"name= "Password"pattern=". {6,20} "pm= "Password must be between 6 and 20 bits"Required="">6         <label>Confirm Password</label>7         <inputtype= "Password"name= "Confirm-pwd">8         <inputID= "Confirm-sign"type= "Submit"value= "Register">9         <P></P>Ten     </form>

The 3rd line above, defines the input of the type= "email", but also to write more than one t= "email" is mainly because IE10 the following browser will not know the type of forced to change to text.

Irrelevant css slightly. With the HTML structure above, you just need to initialize the plugin.

New Form ($ (". Sign-up") [0], {    "error",         // The class name of the fault prompt, used for custom style    errorinputclass: " Invalid ",     //Input Invalid class name for custom style }, submit); function Submit () {    console.log ("form verification successful, ready to submit");     // }

The new from is executed with 3 parameters, the first is the DOM element of the form, the second parameter is some configuration of the validation rule, and the third is the validation of the successful callback function. Corresponds to the following:

var function (Form, checkopt, submitcallback) {       //...}

The second parameter, Checkopt, has two properties Errormsgclass and Errorinputclass are used to customize the style.

The simplest initialization enables the required attribute, pattern attribute, and type validation to take effect. Pattern uses regular expressions, and the error message is placed in the PM attribute, such as the pm= "password between 6 and 20 bits" above.

2. Add a custom test

The above password needs to be guaranteed two times the input is consistent, the checkopt inside adds the custom authentication:

Checkopt.rule = {         "Confirm-pwd": {check:checkpwdidentity,//Custom Check functionmsg: "Two times password input inconsistency"//Error Alert message          } }          functioncheckpwdidentity () {if( This. form["Password"].value!== This. form["Confirm-pwd"].value) {return false; }         return true; }

As shown above, a rule property is added, the key value is the Name property of input, and the value contains a custom validation function and an error message

3. Custom Asynchronous validation

Some data needs to be inspected for service requests, such as verifying that the account exists

CheckOpt.rule.account ={check:checkaccountexist, msg:"Account already exists!", Async:true                         //flag bit, description is asynchronous test};functioncheckaccountexist (Failcallback, successcallback) {varinput = This; Util.ajax ("/register/hasuser", {account: This. Value},function(data) {//Call Failcallback If the user exists, and let the plugin add an error message            if(Data.isuser = = =true) {failcallback (); }            //Success invokes a successful callback function            Else{successcallback ();    }        }); }

In the callback function passed two parameters, if the test failed to execute the first argument, the successful execution of the second parameter, used by the plug-in.

4. Add Custom type Error alert

The form already provides a set of default type error hints:

FORM.PROTOTYPE.VALIDATIONMESSAGE_CN = {    ' invalid mailbox format ',    ' Invalid number format ',    ' Invalid URL format ' ,    ' Invalid format ',    ' invalid format '};

You can also customize one, the above copy can be replaced, temporarily did not provide parameters

In addition, you can cancel the browser-provided copy, with the above default copy

// if the language of the browser is not Chinese, do not use the English copy, bilingual station when applicable checkopt.disablebrowsermsg =! (Navigator.language | | navigator.userlanguage). MATCH (/cn/i)

You can also specify the language in which the form is used:

// when switching between bilingual stations , Checkopt.lang = "cn" is used;  // or en

Third, plug-in source code analysis

The plugin's code is not very complex, but it needs to be considered in many details.

1. Add checkvalidity functions for non-HTML5 browsers

If you don't have a checkvalidity function, add one to it, and the core code is on GitHub, which is not explained in detail here.

    var input = document.createelement ("input");     if (! input.checkvalidity) {        function() {               // detail code See GitHub        }    }

2. Add Error hints

The point is to calculate where the cue appears,

function (input, msg) {}

3. Implementation of asynchronous testing

The difficulty with asynchronous testing is when to execute a submit callback. The solution is to add a Hascheck property to each input and, if checked, set to True to trigger the check once focus is set to False,blur. The submit callback can only be performed if all input has a hascheck of true. The second parameter of the following Checkasync, which is set to True when the point is committed, and false for Blur authentication

1Form.prototype.checkAsync =function(input, doessubmit) {2Name =Input.name;3     varRule =Input.form.Form.checkOpt.rule;4rule[name]["Check"].call (Input,5     //validation Failure callback function6     function(){7         varForm =Input.form.Form;8 form.adderrormsg (input, form.checkopt.rule[name].msg);9     },Ten     //Verify success callback function One     function(){ AInput.hascheck =true; -         if(doessubmit) { - input.form.Form.tryCallSubmit (input); the         } -     }); -};

The 14th line of the code checks whether all input except submit is Hascheck true, and if so, executes the submit callback.

Now this form plugin only supports text/password/url/email/number these types of input, should be able to meet most of the form submission, if necessary, can continue to improve.

Reference:

1. Making HTML5 Form backwards compatible

2. Building HTML5 Form Validation Bubble Replacements

Implement cross-browser HTML5 form validation

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.