Jquery.validate Usage Guide

Source: Internet
Author: User
Tags valid email address

Mainly divided into several parts
Jquery.validate Basic Usage
Jquery.validate API Description
Jquery.validate Custom
Jquery.validate Common types of validation code



Jquery.validate Plugin's document address
Http://docs.jquery.com/Plugins/Validation

Jquery.validate Plugin's homepage
http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Demo available on the Jquery.validate plugin home page
http://jquery.bassistance.de/validate/demo/

validation rules

The following is the default check rule, or you can customize the rule (1) required:true field (2) Remote: "check.php" uses the Ajax method call check.php Validate input value (3) Email:true must enter the correct format of the e-mail ( 4) Url:true must enter the correct format of the URL (5) Date:true must enter the correct format of the date (6) Dateiso:true must enter the correct format of the date (ISO), for example: 2009-06-23, 1998/01/22 only verify the format, No validation validity (7) Number:true must enter a valid number (negative, fractional) (8) Digits:true must enter an integer (9) CreditCard: Must enter a valid credit card number (Ten) Equalto: "#field" input value must and # Field Same (one) Accept: Enter a string with a legal suffix (the suffix of the upload file) maxlength:5 The input length is a string of up to 5 (Chinese characters are counted as a character) (Minlength:10) The string with the minimum input length is 10 ( Chinese characters Count one character) rangelength:[5,10] Enter a string that must be between 5 and 10 "(Chinese characters are counted one character) (range:[5,10] input value must be between 5 and 10 () Max:5 input value cannot be greater than 5 () m In:10 input value cannot be less than 10Validation Tips The following is the default validation prompt, the official website has Simplified Chinese version of the verification prompts to download, or through the Jquery.extend (jQuery.validator.messages custom error message, you can unify the site's validation hint text into a file. Required: "This field was required.", Remote: "Please fix this field.", e-mail: "Please enter a valid email address.", url: "Pl Ease enter a valid URL. ", Date:" Please enter a valid date. ", Dateiso:" Please enter a valid date (ISO). ", Number:" ter a valid number. ", Digits:" Please enter only digits ", CreditCard:" Please enter a valid credit card number. ", Equalto:" P Lease enter the same value again. ", Accept:" Please enter a value with a valid extension. ", MaxLength: $.validator.format (" P Lease enter no more than {0} characters. "), MinLength: $.validator.format (" Please enter at least {0} characters. "), Rangelen Gth: $.validator.format ("Please enter a value between {0} and {1} characters long."), Range: $.validator.format ("Please ENT Er a value between {0} and {1}. "), Max: $.validator.format (" Please enter a value of less than or equal to {0}. "), min: $.valida Tor.format ("Please enter a value greater than or equal to {0}. ")  How to use1: Use default validation rules in controls, example: E-mail (required)
<input id= "Email" class= "required Email" value= "[email protected]"/>
2: You can customize validation rules in controls, examples: custom (required, [3,5]) <input id= "complex" value= "HI" class= "{required:true,minlength:3, Maxlength:5, Messages:{required: ' Why not enter a bit of text ', minlength: ' Too little input ', maxlength: ' Enter so much to do '} '/>3: Custom validation rules through JavaScript, The following JS customizes two rules, password and confirm_password$ (). Ready (function () {$ ("#form2"). Validate ({rules: {passwor                D: {required:true, minlength:5}, Confirm_password: {  Required:true, Minlength:5, Equalto: "#password"}}, messages:            {password: {required: "No password entered", Minlength:jQuery.format ("Password cannot be less than {0} characters")                }, Confirm_password: {required: "No confirmation password", minlength: "Confirm password cannot be less than {0} characters",    Equalto: "Two times input password is inconsistent"}}); Required you can use an expression or a function, such as $ ("#form2"), in addition to True/false. Validate ({rules: {funcvalidate: {required:function () {return $ ("#password"). val ()! = "";}}},messages: {funcvalidate: {required: "must be filled with password"}}); HTML password <input id= "password" name= "password" type= "password"/> Confirm password <input id= "Confirm_password" name= "confirm _password "type=" password "/> condition validation <input id=" Funcvalidate "name=" funcvalidate "value="/>            4: Use meta-custom validation information first set meta$ ("#form3") with JS. Validate ({meta: "validate"}); Htmlemail<input class= "{validate:{required:true, Email:true, messages:{required: ' Enter email address ', email: ' You are not entering a valid e-mail address '}} '/>5: Use Meta to write validation rules within a custom tag, such as Validatejs settings meta$ (). Ready (function () {$.metadata.settype ("    Attr "," validate "); $ ("#form1"). Validate ();}); Htmlemail<input id= "Email" name= "Email" validate= "{required:true, Email:true, messages:{required: ' Enter email address ', Email: ' You are not entering a valid email address '} '/>6: Custom validation rules for complex validation, Custom validation rules can be added via JQuery.validator.addMethod the additional-methods.js contained in the official website contains some commonly used verification methods, such as lettersonly,ziprange,nowhitespace and other examples Character Validation JQuery.validator.addMethod ("UserName", function (value, element{return this.optional (element) | |/^[\u0391-\uffe5\w]+$/.test (value);}, "User name can only include Chinese characters, English letters, numbers and underscores"); You can then use this rule for $ ("#form1"). Validate ({//validation rule rules: {userName: {required:true, UserN Ame:true, Rangelength: [5,10]}},/* Set error message */messages: {userName: {requ  Ired: "Please fill in User name", rangelength: "User name must be between 5-10 characters"}}); Verification of 7:radio, checkbox, select is similar to radio authentication gender <span> male <input type= "Radio" id= "Gender_male" value= "M" Name= "G Ender "Class=" {required:true} "/><br/> female <input type=" Radio "id=" Gender_female "value=" F "name=" gender "/ ></span> checkbox Verification At least two options <span> option 1<input type= "checkbox" id= "Check_1" value= "1" name= "checkg Roup "class=" {required:true,minlength:2, messages:{required: ' Must be selected ', MinLength: ' Select at least 2 items '}} '/><br/> option 2< Input type= "checkbox" id= "Check_2" value= "2" name= "CheckGroup"/><br/> Option 3<input type= "checkbox" id= "Check_3" value= "3" name= "CheckGroup"/><br/></span>select verification drop-down box < span> <select id= "Selectbox" name= "Selectbox" class= "{required:true}" > <option value= "" ></opti On> <option value= "1" >1</option> <option value= "2" >2</option> <option V Alue= "3" >3</option> </select></span>8:ajax verification with remote for AJAX authentication remote: {URL: "url",      //url Address Type: "POST",          // Send As datatype: "JSON",      //Data Format      database: {                 //data to be passed Username:function () {  Return $ ("#username"). val ();}}Plugin Methods 
Custom Selectors Utilities Validator
The 
 Validate method returns a validator object, which has a number of methods that allow you to use the trigger checker or change the contents of a form. The following is a list of commonly used. Form () Returns: Boolean verifies whether the form returns a success or failure element (element) Returns:boolean verifies whether a single element succeeded or failed Resetform () Returns: Undefined restore the previously validated form to the previous state showerrors (errors) returns:undefined display a specific error message  built-in Validation methods
      nametypesetdefaults (defaults) returns:undefined change the default settings Addmethod (name, method, message) Returns: Undefined add a new validation method. Must include a name, a JavaScript method, and a default information Addclassrules (name, rules) returns:undefined add combination validation type Addclassrules (rules) Returns: Undefined adding a combination validation type  built-in Validation methods  
Nametyperequired () Returns:boolean Required validation element required (dependency-expression) Returns:boolean required elements depend on the result of an expression. Required ( Dependency-callback) Returns:boolean the required element depends on the result of the callback function. Remote (URL) returns:boolean requests a remotely verified. The URL is usually a remote call method minlength (length) Returns:boolean set Minimum length maxlength (length) Returns:boolean set Maximum length rangelength (range) Returns:boolean sets a length range [Min,max]min (value) Returns:boolean sets the minimum value. Max (value) Returns:boolean sets the maximum value. Range Returns:boolean setting the range of values email () Returns:boolean Verify the e-mail format URL () Returns:boolean Verify the connection format date () Returns:boolean Verify the date format (similar to 30/ 30/2008 format, do not verify date accuracy validation format only) Dateiso () Returns:boolean develop ISO type date format datede () Returns:boolean Verify the German-style date format (29.04.1994 or 1.1.2006) Number () Returns:boolean Validate decimal digits (including decimals) Numberde () Returns:booleanmakes the element require a decimal numbers wit H German format.digits () Returns:boolean verify integer creditcard () Returns:boolean Verify credit card number accept (extension) Returns: Boolean string Equalto (other) that verifies the same suffix name Returns:boolean Verify that the contents of the two input boxes are the same
Custom Jquery-validate validation behavior 1: Custom form submission Settings Submithandler Customize the form submission action $ (". Selector"). Validate ({submithandler:function (form) {Alert ("validation passed");}); If you need to submit a form, you can call Form.submit (); or $ (form). Ajaxsubmit (); 2: Debug mode sets Debug to True, the form is not submitted, only checks for easy debugging $ (". Selector"). Validate ({debug:true}) 3: Setting the default value of validate use SetDefaults to set the default value for validate, such as all form validation by default is $.validator.setdefaults in debug mode ({Debug:true}) 4: Some elements do not validate the setting ignore property can ignore some elements that do not validate $ (". Selector"). Validate ({ignore: "Ignore"}) 5: Validation timing Jquery.validate can be conveniently set when the validation action is triggered onsubmit: whether to validate $ (". Selector") when committing. Validate ({onsubmit:false}) Onfocusout: Validation (except Checkboxes/radio) $ (". Selector") when the focus is lost. Validate ({onfocusout:false}) onkeyup: Validate $ (". KeyUp") at selector. Validate ({onkeyup:false}) OnClick: Verify when checkboxes, Radio click. $ (". Selector"). Validate ({Onclick:false}) 6: Rewrite validation rules and validation tips// Override the validation hint information for max $.validator.messages.max = Jquery.format ("Your totals Musn ' t exceed {0}!"); /override equal Method $.validator.methods.equal = function (value, element, param) {return value = = param;}; 7:focusinvaliD whether to focus on the last action or the most recent error on $ (". Selector"). Validate ({focusinvalid:false}) 8:focuscleanup If the property is set to true, when the control gets focus, Remove the wrong class definition, hide the error message, and avoid focusinvalid. $ (". Selector"). Validate ({focuscleanup:true}) 9:meta set meta to encapsulate the validation rule $ (". Selector"). Validate ({meta: "Validate",})
<script type= "Text/javascript" ></script>
Customizing how error messages are displayed by default, validation prompts are displayed with a LABEL element, and CSS class is added, which makes it easy to set up error controls and how error messages are displayed. /* Input Control validation error */form input.error {border:solid 1px red;} /* Verify error message */form label.error{width:200px;margin-left:10px; color:red;} If you want to customize the display mode, you can modify the default display of the Jquery.validate by default with the label display error message, you can modify the Errorelement by Errorelement property: HTML tag for error message $ (". Selector" ). Validate errorelement: "em"}) You can wrap a layer of other elements in an error message. Wrapper: The outer envelope of the error message encapsulates the HTML tag $ (". Selector"). Validate ({wrapper: "Li"}) validation error is default to CSS class, which can be modified Errorclass by Errorclass : The CSS class$ (". Selector") used when validating the error. Validate ({errorclass: "Invalid"}) also customizes the action when validation succeeds success: If the value is a string, it will be treated as a CSS class, if it is a function, The function is executed $ (". Selector"). Validate ({success: "valid"}) or success:function (label) {label.html (""). AddClass ("checked");} You can also unify the error message to a container display Errorlabelcontainer: Unifies the error message into a container that displays $ ("#myform"). Validate ({errorlabelcontainer: "#messageBox"})     By default, the error message is placed after the validation element, and you can customize the display location of the error message $ (". Selector"). Validate ({errorplacement:function (error, Element) {   Error.appendto (Element.parent ("TD"). Next ("TD")); }}) moreYou can further define a group, place the error information in a few places in one place, and use the error placement to control where the error message is placed groups: Define a group $ (". Selector"). Validate ({groups: {username: "FName lname"}, Errorplacement:function (error, Element) {if (element.attr ("name") = = "FName" | | element.attr ("nam     E ") = =" LName ") error.insertafter (" #lastname ");   else Error.insertafter (element); }}) Highlighting highlight: Highlighting, by default, adding Errorclassunhighlight: and highlight corresponding, anti-highlighting $ (". Selector"). Validate ({highlight:function (element, Errorclass)     {$ (Element). addclass (Errorclass);  $ (element.form). Find ("label[for=" + element.id + "]"). addclass (Errorclass);     }, Unhighlight:function (element, Errorclass) {$ (Element). Removeclass (Errorclass);  $ (element.form). Find ("label[for=" + element.id + "]"). Removeclass (Errorclass); }}); Or you can fully customize the error display showerrors: Get the wrong display handle $ (". Selector"). Validate ({showerrors:function (Errormap, errorlist) {$ ("#summary") ). HTML ("Your form contains" + this.numberofinvalids () + "errors, see details below."); This.defaultshowerRors (); }})
<script type= "Text/javascript" ></script>//mobile number verification JQuery.validator.addMethod ("mobile", function (value, Element) {    var length = value.length;    var mobile = /^ ((13[0-9]{1}) | ( 15[0-9]{1})) +\d{8}) $/    return this.optional (element) | | (length = = && Mobile.test (value)), "Cell phone number format error");  //Phone number verification    JQuery.validator.addMethod ("Phone", function (value, Element) {    var tel =/^ (0[0-9]{2,3}\-)? ( [2-9] [0-9] {6,7}) + (\-[0-9]{1,4})?$/;    return this.optional (element) | | (Tel.test (value));}, "Malformed phone number");//ZIP code validation    jQuery.validator.addMethod ("ZipCode", function (value, Element) {    var tel =/^[0-9]{6}$/;    return this.optional (element) | | (Tel.test (value)), "Bad Postal Code format");//QQ number verification    JQuery.validator.addMethod ("QQ", function (value, Element) {     var tel =/^[1-9]\d{4,9}$/;    return this.optionAl (Element) | | (Tel.test (value));}, "QQ number format error");//IP Address authentication jQuery.validator.addMethod ("IP", function (value, Element) {     var IP =/^ (?:(? : 25[0-5]|2[0-4][0-9]| [01]? [0-9] [0-9]?) \.) {3} (?: 25[0-5]|2[0-4][0-9]| [01]? [0-9] [0-9]?) $/;    return this.optional (element) | | (Ip.test (value) && (regexp.$1 < Rege && regexp.$2 < regexp.$3, &&, < &&, and more.) Xp.$4 <));}, "IP address format error");//verification of letters and numbers JQuery.validator.addMethod ("Chrnum", function (value, Element) {     var chrnum =/^ ([a-za-z0-9]+) $/;    return this.optional (element) | | (Chrnum.test (value)), "Enter only numbers and letters (characters A-Z, A-Z, 0-9)");//chinese Validation jQuery.validator.addMethod ("Chinese", Function (value, Element) {    var Chinese =/^[\u4e00-\u9fa5]+$/;    return this.optional (element) | | (Chinese.test (value));}, "can only input Chinese");//drop-down box to verify $.validator.addmethod ("Selectnone", function (value, Element) {     return value = = "Please select";}, "must select an item");//Byte length validation jQuery.validator.addMethod ("Byterangelength", function (value, element, param) {     var length = value.length;    for (var i = 0; i < value.length; i++) {&NBSP;&NBSP;&NBSP;&NBSP;&NB sp;   if (value.charcodeat (i) > 127) {             length++;       }   }    return This.optional (Element) | | (length >= param[0] && length <= param[1]);}, $.validator.format ("Make sure the value entered is between {0}-{1} bytes (2 bytes in one text)");

Jquery.validate Usage Guide

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.