JQuery Validate form Validation deep learning _jquery

Source: Internet
Author: User
Tags commit dateformat wrapper

The previous article introduced the basics of the introduction of jquery validate form validation, detailed in the jquery validate form validation Primer, today's article delves into jquery Validate form verification, the following are the full contents of the article:

1, in other ways to replace the default SUBMIT

$ (). Ready (function () {
 $ ("#signupForm"). Validate ({
  submithandler:function (form) {
   alert ("submitted") ; 
   Form.submit ();}});

Using AJAX methods

 $ (". Selector"). Validate ({  
 submithandler:function (form) 
 {  
  $ (form). Ajaxsubmit ();  
 } 
 ) 

You can set the default value for validate, as follows:

 $.validator.setdefaults ({
 submithandler:function (form) {alert ("submitted!"); Form.submit (); }
});

If you want to submit a form, you need to use Form.submit () instead of $ (form). Submit ().
2, Debug, only validation does not submit the form
If this argument is true, the form is not submitted, is checked, and is easy to debug.

$ (). Ready (function () {
 $ ("#signupForm"). Validate ({
  debug:true
 });

If more than one form in a page wants to be set to debug, use:

$.validator.setdefaults ({
 debug:true
})

3, ignore: Ignore some elements do not verify
Ignore: ". Ignore"
4, change the location of the error message display
Errorplacement:callback
indicates where the error was placed, by default: Error.appendto (Element.parent ()), where the error message is placed behind the validated element.

Errorplacement:function (Error, Element) { 
 error.appendto (element.parent ()); 
}

Instance

<tr> <td class= "label" ><label id= "Lfirstname" for= "FirstName" >first name</label></td> &LT;TD class= "field" ><input id= "FirstName" name= "FirstName" "type=" text "value=" "maxlength=" > <td class= "status" ></td> </tr> <tr> <td style= "padding-right:5px;" > <input id= "dateformat_eu" name= "DateFormat" type= "Radio" value= "0"/> <label id= "Ldateformat_eu" for= "da Teformat_eu ">14/02/07</label> </td> <td style=" padding-left:5px; > <input id= "dateformat_am" name= "DateFormat" type= "Radio" value= "1"/> <label id= "ldateformat_am" for= "da Teformat_am ">02/14/07</label> </td> <td></td> </tr> <tr> <td class=" label " > </td> <td class= "field" colspan= "2" > <div id= "termswrap" > <input id= "terms" type= "Che Ckbox "name=" terms "/> <label id=" lterms "for=" terms ">i have read and accept the TErms of use.</label> </div> </td> </tr> errorplacement:function (Error, Element) {if (eleme
 Nt.is (": Radio")) Error.appendto (Element.parent (). Next (). Next ());
 else if (element.is (": CheckBox")) Error.appendto (Element.next ());
Else Error.appendto (Element.parent (). Next ());

 }

The role of code is: In general, the error message is displayed in the <td class= "status" ></td>, if Radio is displayed in <TD ></td>, if a checkbox is displayed after the content.
Parameters   Types   Description   Defaults
errorclass string  Specifies the CSS class name for the error hint, and you can customize the style of the error hint.   "error"
errorelement string  tag error with what label, default is label, can be changed to EM.   "label"
errorcontainer selector  Display or hide validation information, you can automatically implement the error message appears when the container properties into a display, no error hidden, not very useful.
Errorcontainer: "#messageBox1, #messageBox2" &NBSP;
errorlabelcontainer selector  put the error message uniformly in a container. &NBSP
wrapper string  with what label to wrap up the errorelement above. &NBSP
Typically these three properties are used at the same time, implementing the ability to display all the error hints within a container, and are automatically hidden when there is no information.
Errorcontainer: "Div.error",
Errorlabelcontainer: $ ("#signupForm div.error"),
Wrapper: "Li"
5 , change the style of the error message display
to set the style of the error hint, you can increase the icon display, in the system has established a VALIDATION.CSS, dedicated to maintaining the style of the checksum file.

Input.error {border:1px solid red;}
Label.error {
 Background:url ("./demo/images/unchecked.gif") no-repeat 0px 0px;

 padding-left:16px;

 padding-bottom:2px;

 Font-weight:bold;

 Color: #EA5200;
}
label.checked {
 Background:url ("./demo/images/checked.gif") no-repeat 0px 0px;


6, each field validation through the execution function
Success:string,callback
The element to be validated is validated by an action that, if followed by a string, is treated as a CSS class, and can be followed by a function.

Success:function (label) {
 //Set as text for IE
 label.html (""). AddClass ("checked");
 Label.addclass ("valid"). Text ("ok!")
}

Add "valid" to the validation element, the style defined in the CSS <style>label.valid {}</style>.
Success: "Valid"
7, the validation of the trigger method modification
the following, although Boolean, is not recommended unless you want to change to false.
Trigger mode type Description Default value
OnSubmit Boolean Commit-time validation. Set to False to validate it in other ways. True
Validation (excluding check boxes/radio buttons) when Onfocusout Boolean loses focus. True
OnKeyUp Boolean is validated at keyup time. True
The onclick Boolean is validated when the check box and radio button are clicked. True
Focusinvalid when a form is submitted, a form that is not validated (the first or the failed form that has the focus before it is submitted) receives the focus. True
Focuscleanup Boolean If this is true, remove the error prompt when the element that fails validation obtains the focus. Avoid working with Focusinvalid. False

Resets
the form $ (). Ready (function () {
 var validator = $ ("#signupForm"). Validate ({
  submithandler:function (form) {
   alert ("submitted"); 
   Form.submit ();
  } 
 );
 $ ("#reset"). Click (function () {
  validator.resetform ();});



8. Asynchronous verification
Remote:url
Using Ajax for validation, the default is to commit the currently validated value to the remote address, and you can use the data option if you need to submit additional values.

Remote: "check-email.php"
remote: {
 URL: "check-email.php",  //Background handler
 type: "POST",///    Data send mode
 dataType: "JSON",   //Accept Data format 
 : {      //data to be passed
  username:function () {return
   $ ("#username" ). val ();}}

Remote addresses can only output "true" or "false" and cannot have other outputs.
9. Add Custom Checksum
Addmethod:name, method, message
Custom Validation Methods

Chinese text two bytes
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 that the value entered is between {0}-{1} bytes (2 bytes in a literal)." "));

ZIP Code verification 
JQuery.validator.addMethod ("Iszipcode", function (value, Element) { 
 var tel =/^[0-9]{6}$/;
 return this.optional (Element) | | (Tel.test (value);
}, "Please fill in your zip code correctly");

Note: To add or add to the Additional-methods.js file in the Jquery.validate.js file. Recommendations are generally written in the Additional-methods.js file.
Note: add: Iszipcode: "Only include Chinese characters, English letters, numbers, and underscores" in the Messages_cn.js file. Add a reference to the Additional-methods.js file before calling.
10, Radio and checkbox, select Verification
Radio's required indicates that one must be selected.

<input type= "Radio" id= "Gender_male" value= "M" name= "gender" class= "{required:true}"/> <input "type=" id
= The/> Representation of the "Gender_female" value= "F" name= "gender" required checkbox must be selected. <input type= "checkbox" class= "checkbox" id= "Agree" Name= "agree" class= "{required:true}"/> checkbox
Represents the minimum number that must be selected, MaxLength represents the maximum number of checks, and rangelength:[2,3] indicates the range of selected numbers. <input type= "checkbox" class= "checkbox" id= "Spam_email" value= "email" name= "spam[" "class=" {required:true, Minlength:2} "/> <input type= checkbox" class= "checkbox" id= "Spam_phone" value= "Phone" name= "spam[" "/> < 
Input type= "checkbox" class= "checkbox" id= "Spam_mail" value= "Mail" name= "spam[]"/> Select's required indicates that the selected value cannot be empty. <select id= "Jungle" Name= "Jungle" title= "Please select something!" class= "{required:true}" > <option value= "" & Gt;</option> <option value= "1" >Buga</option> <option value= "2" >Baga</option> < Option value= "3" >Oi</option> </seThe minlength of the lect> select represents the minimum number selected (selectable Select), maxlength represents the maximum number of selections, and rangelength:[2,3] represents the selected range. <select id= "fruit" name= Fruit "title=" Please select at least two "fruits" {class=, required:true} "Minlength:2 E= "multiple" > <option value= "b" >Banana</option> <option value= "a" >Apple</option> <
 Option value= "P" >Peach</option> <option value= "T" >Turtle</option> </select>

Appendix: Built-in Verification Method:

This article has been organized into the "jquery form verification Encyclopedia," Welcome to learn to read.

The above is for jquery validate form verification of in-depth study, I hope to help you learn.

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.