jquery-Form Validation plug-in-validation

Source: Internet
Author: User

▓▓▓▓▓▓ approximate Introduction

  The JQuery Validate plugin provides a powerful validation feature for forms, making it easier to validate client forms, while providing a number of customization options to meet the needs of your application. The plugin bundles a set of useful validation methods, including URL and email validation, and provides an API to write user-defined methods. All bundled methods use English as an error message by default and are translated into 37 other languages. The plugin was written and maintained by J?rn Zaefferer, a member of the jquery team, the main developer of the jquery UI team and the maintainer of qunit. The plugin began to appear in the early days of JQuery in 2006 and has been updated so far. Visit the jquery Validate website and download the latest version of the jquery Validate plugin.

: Http://static.runoob.com/download/jquery-validation-1.14.0.zip

▓▓▓▓▓▓ Basic Syntax

Validate plugin requires jquery, so we need to introduce jquery and validate files in the head

1     <script type= "Text/javascript" src= "lib/jquery.js" ></script>2 <script     type= "text/ JavaScript "src=" Dist/jquery.validate.min.js "></script>

  

After the file is introduced, write a simple form

 1 <form class= "Cmxform" id= "Commentform" method= "Get" > 2 <fieldset> 3 <legend> validate complete Form < /legend> 4 <p> 5 <label for= "FirstName" > Name </label> 6 <input id= "Firstn Ame "Name=" FirstName "type=" text "> 7 </p> 8 <p> 9 <label for=" LastName "> Last Name & LT;/LABEL&GT;10 <input id= "LastName" Name= "LastName" type= "text" >11 </p>12 <p> <label for= "username" > user name </label>14 <input id= "username" name= "username" type= "text" >15 </p>16 <p>17 <label for= "password" > password </label>18 <inp UT id= "password" name= "password" type= "password" >19 </p>20 <p>21 <label for= "c Onfirm_password "> Verify password </label>22 <input id=" Confirm_password "name=" Confirm_password "type=" password " >23 </p&gt, <p>25 <label for= "email" >email</label>26 <input id= "email" name= "Emai            L "type=" email ">27 </p>28 <p>29 <label for=" Agree "> Please agree to our statement </label>30 <input type= "checkbox" class= "checkbox" id= "Agree" Name= "agree" >31 </p>32 <p> <input class= "Submit" type= "Submit" value= "commit" >34 </p>35 </fieldset>36 &L T;/form>

Then we begin to write the code of the Verification form

First we need to know that the form needs to be verified.

1         $ (function () {2 3             $ (' #commentForm '). Validate (); 4 5         });

Then start writing validation rules, note that the selection element here is based on the Name property of each tag, and the basic syntax is as follows

1             $ (' #commentForm '). Validate ({2                 rules: {3                     FirstName: ' Required ',//required = Required field 4                     LastName: {5                         required:true,6                         minlength:3//Minimum length is PNS                     }8                 }9             });

 

As can be seen from the above, if a message only a validation requirements can be written in one line, such as FirstName, if there is more than one validation to write a form like LastName; know the basic syntax

Look at the validation, they're all providing the calibration rules.

(1), Required:true               must lose field (2), Remote: "remote-valid.jsp"   using Ajax method call remote-valid.jsp Validation input value (3), Email:true                  Must enter the correct format of e-mail (4), Url:true                    must enter the correct format of the URL (5), Date:true                   must enter the correct format of the date, the date check IE6 error, with caution (6), Dateiso:true                You must enter the correct format for the date (ISO), for example: 2009-06-23, 1998/01/22 only verify the format, do not validate the validity (7), Number:true                 must enter a valid number (negative, decimal) (8), Digits:true                 Must enter an integer (9), Creditcard:true             must enter a valid credit card number (10), Equalto: "#password"        input value must be the same as #password (11), Accept:                    Enter a string with a valid suffix name (the suffix of the uploaded file) (12), a string with a                maximum input length of 5 (Kanji maxlength:5 one character) (13), and a string with a               minimum length of 10 for the Minlength:10 input (Chinese characters are counted as one character) (14), rangelength:[5,10]         The input length must be between 5 and 10 string ") (Chinese characters counted one character) (15), range:[5,10]               input values must be between 5 and 10 (16), Max:5                      Input value cannot be greater than 5 (17), Min:10                     input value cannot be less than 10

We will complete the above form verification, as follows

 1 $ (function () {2 3 $ (' #commentForm '). Validate ({4 rules: {5 6 FirstName: {7 Required:true, 8 Minlength:5 9},10 One lastname: "Required", Username: {required:true                         , rangelength: [4,6]16},17 Password: {19                     required:true,20 minlength:4,21 Number:true22                         },23 Confirm_password: {required:true,26 minlength:3,27 equalto: ' #password '},29 email: {3                 1 required:true,32 email:true33},34 35 }36}); 37}); 

Effect:

You can see that the hints here are not very satisfactory by default in English, there are two ways to change the information into Chinese

  First approach: Introducing language files (recommended)

1     <script type= "Text/javascript" src= "Dist/localization/messages_zh.js" ></script>

His cue message is:

1     Required: "This is a required field", 2     Remote: "Please fix this field", 3     Email: "Please enter a valid e-mail address", 4     URL: "Please enter a valid URL", 5     Date: " Please enter a valid date ", 6     dateiso:" Please enter a valid date (YYYY-MM-DD) ", 7     Number:" Please enter a valid digit ", 8     digits:" Only enter the number ", 9     CreditCard: "Please enter a valid credit card number",     equalto: "Your input is not the same", one     extension: "Please enter a valid suffix",     maxlength: $.validator.format (" You can enter a maximum of {0} characters "),     minlength: $.validator.format (" Minimum of {0} characters to enter "),     rangelength: $.validator.format (" Please enter a string of length between {0} and {1} '),     Range: $.validator.format ("Enter a value from {0} to {1}"), and     Max: $.validator.format (" Please enter a number not greater than {0} "),     min: $.validator.format (" Please enter a number not less than {0} ")

 The second way: Write your own cue message

 1 $ (' #commentForm '). Validate ({2 rules: {3 4 firstname: {5 Required:true, 6 Minlength:5 7}, 8 9 last                         Name: "Required", ten Username: {required:true,13 Rangelength: [4,6]14},15 password: {required:true                     , minlength:4,19 Number:true20},21 22                         Confirm_password: {required:true,24 minlength:3,25 Equalto: ' #password '},27 email: {$ r equired:true,30 email:true31}32},33 messag              es: {34 35            FirstName: "Please enter your name", LastName: "Please enter your surname", PNs Username: {38                          Required: "Please enter user name", minlength: "User name must consist of two letters" 40                            },41 Password: {required: "Please enter your password", 43                            MinLength: "Password length cannot be less than 5 letters"},45 Confirm_password: {46                            Required: "Please enter password", minlength: "Password length can not be less than 5 letters", 48                        Equalto: "Two times password input inconsistent"},50 email: "Please enter a correct mailbox", 51 }52});

    

Effect:

  Note: There is also a way to write validation that is written in class, such as

          <input id= "FirstName" name= "FirstName" type= "text" class= "{required:true, minlength:2}" >

However, this is not recommended because it does not conform to the requirements of style and structure separation, and it is necessary to download a jquery.metadata.js file yourself to write this

▓▓▓▓▓▓ form Submission Issues

You can execute our custom code before the form is submitted, and then submit the form when our custom code finishes executing

1             $ (' #commentForm '). Validate ({2 3                 submithandler:function () {4                     alert ("Commit event Success"), 5                     from.submit (); 6                 }7                             });

You can set the default value for validate

1         $.validate.setdefaults ({2             submithandler:function () {3                 alert ("submitted successfully! "); 4                 form.submit (); 5             }6         });

Validate not submit form only

1         $ (function () {2          $ ("#commentForm"). Validate ({3                 debug:true;4             }); 5         });

▓▓▓▓▓▓ error Message Settings

  1. Error message location settings

The Errorplacement method is to set where the error message is displayed, and the default value is after the validation element

1         errorplacement:function (Error, Element) {  2             error.appendto (Element.parent ());  3         }

Errorclass is the style that sets the error message, followed by the CSS class name

Errorelement is set with what label to wrap the error message, the default value is <label>

Errorlabelcontainer is set to have all the error messages wrapped in one place

Wrapper is set up with what label and then wrap up the top errorelement

For example:

1                 errorplacement:function (error,element) {2                     $ (element). Closest (' form '). Find (' label[for= ' + element.attr ( "id") + '] '). Append (Error); 3                 },

is to display the error message in front of the validated information

Effect:

For example:

1                 errorelement: ' span ', 2                 errorclass: ' Commenterror ', 3                 errorlabelcontainer: $ (' Form Div.error '), 4                 Wrapper: ' Li ',

is to wrap each hint with a <span> tag and give them a CSS named. Commenterror style, and wrap them all in a div with a class error, and use <li> to wrap up each cue message

Effect:

  2. Error message style settings

There are two ways to modify the style of the cue message

The first is to use the style file that comes with the download validation

1     <link href= "demo/css/screen.css" type= "Text/css" rel= "stylesheet"/>

  

The second way is to define your own style (you can modify your own CSS file, of course)

For example, add a style like this:

1         input.error {border:1px solid red;} 2         label.error {3           background:url ("Demo/images/unchecked.gif") No-repeat 0px 0px; 4  5           padding-left:16px; 6  7           padding-bottom:2px; 8  9           font-weight:bold;10 One           color: # ea5200;12         }13         label.checked {           background:url ("demo/images/checked.gif") no-repeat 0px 0px;15         }

Effect:

▓▓▓▓▓▓ Validation Issues

  1. Validated elements are passed

Validation of the element through validation if you want to operate, you can use success, he can accept a string or a function, when the string is accepted when the style is added

For example:

                Success:function () {                    alert (1);                },

is when the element to be validated passes validation, the popup 1

For example:

           Success: "Valid"    

is to add a CSS style named. Valid to the element

  

  2. Verification method

▓▓▓▓▓▓ Custom Checksum

Although validation provides many ways to verify, there are some situations that are not enough, so if you want to add a custom checksum, you can use the Addmethod method, usually writing a custom method in additional-methods.js. And then we're going to introduce this file

    <script type= "Text/javascript" src= "Dist/additional-methods.js" ></script>

Write the contents of the Additional-methods.js file

For example:

1 $.validator.addmethod ("Iszipcode", function (value, Element) {   2     var tel =/^[0-9]{6}$/;3     return This.optional (Element) | | (Tel.test (value)); 4}, "Please fill in your zip code correctly");

Just write this code into the additional-methods.js file and you can use the

  For example:

1                     zipcode: {2                         required:true,3                         iszipcode:true4                     }

Effect:

Validation of ▓▓▓▓▓▓radio and checkbox, select

The required of radio indicates that you must select a

The required of a checkbox must be selected, minlength indicates the minimum number that must be selected, MaxLength indicates the maximum number that must be selected, rangelength[2,3] indicates the number of bands selected

The required of select indicates that the selected value cannot be empty, minlength indicates the minimum number that must be selected, MaxLength indicates the maximum number that must be selected, rangelength[2,3] indicates the number of bands selected

  Summary : The validation plugin provides a lot of validation, and users can add their own style of validation and cue information, but in the blog I did not mention Ajax-related content, because Ajax has not learned-_-| |, if there is any problem can be discussed with me, If there is a wrong place, please correct me.

jquery-Form Validation plug-in-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.