Form Validation Plugin Jquery.validata use method

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 TipsThe 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}. ") Basic Usage1: 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: {password: {               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")}, Confir M_password: {required: "No confirmation password", minlength: "Confirm password cannot be less than {0} characters", Equalto: "Two times input password not    Consistent "}}}); Required you can also use an expression or function, such as $ ("#form2"), in addition to True/false. Validate ({rules: {funcvalidate: {required:function () {Retu RN $ ("#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"}}); 7:radio, checkbox, select are verified similarly (1) Radio authentication gender <span> male <input type= "Radio" id= "Gender_male" value= "M" Name= "Gender" class= "{required:true}"/><br/> female <input type= "Radio" id= "Gender_female" value= "F" name= "gender"/ ></span> (2) checkbox verification At least two options <span> option 1<input type= "checkbox" id= "Check_1" value= "1" namE= "CheckGroup" class= "{required:true,minlength:2, messages:{required: ' Must be selected ', MinLength: ' Select at least 2 items '}}"/><br/ > Options 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> (3) Select Verification drop-down box <span> < Select Id= "Selectbox" name= "Selectbox" class= "{required:true}" > <option value= "" ></option> &L T;option value= "1" >1</option> <option value= "2" >2</option> <option value= "3" >3&lt ;/option> </select></span>
8:ajax authentication with remote for AJAX authentication remote: {URL: "url",//url address Type: "POST",//Send As datatype: "JSON",//Data format
Data: {//Username:function () {return $ ("#username") to be passed. Val ();}}
APIPlugin Methods
 Name typevalidate (options) returns:validator Verify the selected Formvalid () retur Ns:boolean checks whether validation rules ("Add", "rules") returns:options add validation rules through rules () returns:options return elements rule S ("Remove", rules) returns:options Delete validation rules removeattrs (attributes) returns:options remove special attributes and return them  Custom Selectors  Name Type:blank Returns:array <element > No value filter: Fil LED Returns:array <element > Filter with value: Unchecked Returns:array <element > Sieve of Elements not selected Selector  Utilities  Name typejquery.format (template, argument, AR Gumentn ...) Returns:string replaces {n} in the template with a parameter.  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  Name typesetdefaults (defaults) returns:undefined changes 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  
Name typerequired () Returns:boolean Required validation element required (dependency-expr                   Ession) Returns:boolean the required element depends on the result of the expression. Required (Dependency-callback) Returns:boolean required elements depend on the result of the callback function. Remote (URL) Returns:boolean request remote Check. A URL is usually a remote call method minlength (length) Returns:boolean sets the minimum length maxlength (length) Returns:boolean Set Maximum length rangelength (range) Returns:boolean set a length range [Min,max]min (value) Returns:bo Olean sets the minimum value. Max (value) Returns:boolean sets the maximum value. Range Returns:boolean Set value for                                 Mail () Returns:boolean verify the e-mail format URL () Returns:boolean Verify the connection format date () Returns:boolean Verify date format (similar to 30/30/2008 format, do not verify date accuracy only validate format) Dateiso () Ret Urns:boolean development of 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 Ele                        ment require a decimal number with German format.digits () Returns:boolean Validate integer CreditCard ()                Returns:boolean Verify the credit card number accept (extension) Returns:boolean to verify the same suffix name of the string Equalto (other) 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 validation rule $ (". Selector"). Validate ({meta: "Validate",})
10: Custom error message display by default, the validation prompt is displayed with a LABEL element, and a CSS class is added, which makes it easy to set the error control and how the error message is 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")); }}) Further, you can define a group, place the error information in several 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 ("name") = = "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 (); }})

Common validation Codes
//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));
}, "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));
}, "wrong phone number format");

//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+ +) {        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)");

Form validation Plug-in jquery.validata usage

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.