jquery's Validate validation plugin use method

Source: Internet
Author: User
Tags valid email address

(1) default check rule
(1) Required:true must lose field
(2) Remote: "check.php" using Ajax method call check.php Validate 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 date
(6) Dateiso:true must enter the correct format for the date (ISO), for example: 2009-06-23, 1998/01/22 only verify the format, do not verify the 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
Equalto: The "#field" input value must be the same as #field
(one) Accept: Enter a string with a valid suffix (the suffix of the uploaded file)
Maxlength:5 input string with a maximum length of 5 (Chinese characters are counted as one character)
(minlength:10) Enter a string with a minimum length of 10 (Chinese characters are counted as one character)
(rangelength:[5,10] Enter a string that must be between 5 and 10 in length) (Chinese characters are counted as one character)
(range:[5,10] Input value must be between 5 and 10
(+) Max:5 input value cannot be greater than 5
(min:10) input value cannot be less than 10

(2)The default hints
Messages: {
Required: "This field is required.",
Remote: "Please fix this field.",
Email: "Please enter a valid email address."
URL: "Please enter a valid URL.",
Date: "Please enter a valid date.",
Dateiso: "Please enter a valid date (ISO).",
Datede: "Bitte geben Sie ein G eyebrow ltiges Datum ein.",
Number: "Please enter a valid number.",
Numberde: "Bitte geben Sie eine Nummer ein.",
Digits: "Please enter only digits",
CreditCard: "Please enter a valid credit card number.",
Equalto: "Please enter the same value again.",
Accept: "Please enter a value with a valid extension.",
MaxLength: $.validator.format ("Please enter no more than {0} characters."),
MinLength: $.validator.format ("Please enter at least {0} characters."),
Rangelength: $.validator.format ("Please enter a value between {0} and {1} characters long."),
Range: $.validator.format ("Please enter a value between {0} and {1}."),
Max: $.validator.format ("Please enter a value of less than or equal to {0}."),
Min: $.validator.format ("Please enter a value greater than or equal to {0}.")
},

(3)

Custom validation Rules:

$ (document). Ready (function(){                    $("#empForm"). Validate ({//validation rulesrules:{realname:"Required", username:{required:true, rangelength:[5,8]}, psw:{required:true, rangelength:[6,12]}, psw2:{required:true, Equalto:"#psw"}, gender:{required:true}, age:{digits:true, range:[10,15]}, edu:{required:true}, birthday:{required:true, Date:true}, checkbox1:{required:true}, email:{email:true}, cart:{Cardcheck:"2"                  }              },                            //Prompt Informationmessages:{realname:"Real name cannot be empty", username:{required:"Login name cannot be empty", Rangelength:"Login length is from 5 to 8"}, psw:{required:"Password cannot be empty", Rangelength:"Password length is from 6 to 12"}, psw2:{required:"Confirm password cannot be empty", Equalto:"Two times password input inconsistency"}, gender:{required:"Please select Gender"}, age:{digits:"The input must be a number", Range:"Age must be between 10-15"}, edu:{required:"Education must choose one"}, birthday:{required:"Birthday must be filled in", Date:"Date format is 1900/01/01"}, checkbox1:{required:"Must choose"}, email:{email:"The mailbox format is incorrect"                  }              },                            //actions to validate after successSuccessfunction(label) {label.html (""). AddClass ("right");//the quotes are & nbsp;             }                                      });          }); //Custom validation rules        /** Addmethod: * The first parameter is: the name of the validation method, which will be used in rules and messages * The second parameter is: Callback method * First parameter: value in component * Second parameter element: Component Object * Third parameter: Indicates error message if me The error message is also written in the ssages, so the message will be overwritten.*/$.validator.addmethod ("Cardcheck",function(value,element,params) {//alert ("Value--->" +value); Is the value of the text box input//alert ("Element--->" +element); Component Objects//alert ("Params--->" +params); Default value 2 in rules Cart:{cardcheck: "2"}            if(value!=NULL){                  if(value.length>=15&&value.length<=18)                      return true; }Else{                  return false; }          },"error message");

Verify the style after success:

/**/      label.right{margin-left:4px; padding-left:20px; Background:url ( checked.gif) no-repeat 2px 0;vertical-align:middle;}  

[HTML]View Plaincopyprint?
inch-Main demo</title> <link rel= "stylesheet" type= "text/css" media= "screen" href= "Css/screen.css"/> <script type= "Text/javascript" src= "js/jquery-1.4.2.js" ></script> <script type= "Text/javasc Ript "src=" js/jquery.validate.js "></script> <script type=" Text/javascript ">//Add here</script> Label Style= "Display:none" for= "Gender" class= "error"your gender must choose a label*Label : is the label that displays the error message in jquery* class= "Error"property represents the error message that holds the* The For property represents the unique identity of the tag, and the jquery validation framework runs with the for= "gender"find lable tags for conditions*if found, use directly*if not found, create a new label on the label style= "Display:none" for= "Gender" class= "error"The underlying code errorclass:"Error", Errorelement:"Label", the label= $ ("<" + This. settings.errorelement + "/>")----$ ("<label/>"). attr ({"For": This. Idorname (Element), generated:true}). addclass ( This. Settings.errorclass). Text (Message|| ""); Label=<label for= "The value of the Name property" class= "Error" >xxxxx</label> <tr> <td> Gender (must be selected) </td> <td> <input Typ E= "Radio" id= "Gender_male" value= "M" name= "gender"/> Male <input type= "Radio" id= "Gender_female" V Alue= "F" name= "gender"/> Female <!--This tag is written to prevent the default message from being displayed next to ' Man '--<label Style= "Display:none" for= "Gender" class= "error" > Your gender must select a </label> </td> &LT;/TR&G              T <tr> <td> Ages (required 26-50):</td> <td><input type= "text" id= "Age" NA Me= "Age"/></td> </tr> <tr> <td> your education: &L t;/td> <td> <select name= "edu" id= "edu" > <option value= "" >--Please Select Your education--</option> <option value= "A" > Specialties </option> <option V Alue= "B" > Undergraduate </option> <option value= "C" > graduate student </option> &lt                    Option value= "E" > Master </option> <option value= "D" > PhD </option>                 </select> </td> </tr> <tr> <td> Date of birth (1982/09/21):</td> <td><input type= "text" id= "Birthday" name= "Birthday" style= "Widt h:120px "value=" "/></td> </tr> <tr> <td&gt Hobbies:</td> &LT;TD colspan= "2" > <input type= "checkbox" Name= "CheckBox1" id=                     "Qq1"/> Table tennis <input type= "checkbox" Name= "CheckBox1" id= "QQ2" value= "1"/> Badminton <input type= "checkbox" Name= "CheckBox1" id= "Qq3" value= "2"/> Internet <input type= "checkbox" Nam  E= "CheckBox1" id= "Qq4" value= "3"/> Travel <input type= "checkbox" Name= "CheckBox1" id= "Qq5" value= "4" /> Shopping <!--This label is written to prevent the default from displaying the message next to ' ping pong '-<label style= "Display:none  " for= "CheckBox1" class= "error" > Your hobbies, select at least one </label> </td> </tr> <tr> <td align= "left" > E-mail:</td> <td><input type= "text                     "id=" email "style=" width:120px "name=" email "/></td> </tr> <tr> &LT;TD align= "left" > ID (15-18):</td> <td><input type= "text" id= "cart" s Tyle= "width:120px" name= "cart"/></td> </tr> <tr> &LT;TD ></td> <td></td> <td><input type= "Submit" Name= "FirstName "Id=" FirstName "value=" Save ></td> </tr> </table> </form> &LT;/BODY&G  T 

Precautions:

1. Import the Validate.js file

Attention:

*validate.js must be imported after the Jquery.js file because the method defined in Jquery.js is required in the validation framework

* If you import jquery.js and import Validate.js again, import the Jquery.js again. Because some methods are extended in the validation framework, and then imported jquery.js will overwrite the extended method.

2. Specify the components to validate

Attention:

* Write the validated code in $ (document). Ready (function () {...}) or $ (function () {...}) function, because it must wait until all the DOM structure is finished before it can be executed, or it will error, the element cannot be found.

3. Add the class attribute on the component to be validated

Attention:

Using class= "{}", the package must be introduced: Jquery.metadata.js can modify the prompt using the following methods:
Class= "{required:true,minlength:5,messages:{required: ' Please enter content '}}" when using the Equalto keyword, the following must be enclosed in quotation marks, as follows:
Class= "{required:true,minlength:5,equalto: ' #password '}"

* There are two ways to add class attributes to a component:

1.class= "required Email" multiple rules are separated by spaces

2.class= "{required:true,email:true}" JSON format

Of course, you can also mix class= "{required:true} email"

To make a separate prompt message overlay:

[JavaScript]View Plaincopyprint?
Name <input type= "text" name= "UserName" class= "{required:true,minlength:3,messages:{required: ' name required ', minlength: ' cannot be less than 3 words '}} ' >  
[JavaScript]View Plaincopyprint?
<script type= "Text/javascript" >//custom validation Prompt messageJquery.extend (jQuery.validator.messages, {required:"Please fill in this field", Remote:"Validation Failed", Email:"Please enter the correct email", URL:"Please enter the correct URL", Date:"Please enter the correct date", Dateiso:"Please enter the correct date (ISO).", Number:"Please enter the correct number", digits:"Please enter the correct integer", CreditCard:"Please enter the correct credit card number", Equalto:"Please enter the same value again", Accept:"Please enter a string for the specified suffix name", Maxlength:jQuery.validator.format ("Maximum allowed length is {0} characters"), Minlength:jQuery.validator.format ("The minimum allowable length is {0} characters"), Rangelength:jQuery.validator.format ("Allowed lengths are between {0} and {1}"), Range:jQuery.validator.format ("Please enter a value between {0} and {1}"), Max:jQuery.validator.format ("Please enter a value of max {0}"), Min:jQuery.validator.format ("Please enter a value of minimum {0}")      }); $ (document). Ready (function(){          $("Form"). Validate ();  }); </script>[JavaScript] View Plaincopyprint? <style type= "Text/css" >/*the label component of the Class=error*/label.error{margin-left:10px;      color:red; }  </style>

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.