jquery Validate Plugin Usage tips

Source: Internet
Author: User

The function of data checking is often used to make Web forms. JavaScript validation is a relatively common method. Recently write page write more, found a more useful JS check frame--jquery.validate. She is a jquery-based verification tool that basically satisfies most of our page verification needs and supports AJAX validation. Supports a variety of custom extensions, including custom check rules, customizing how errors are displayed, and so on.

With a period of time, the feeling is very simple to use. Here is a brief introduction to how to use the method, and then introduce a kind of my own extension of a way of error (feel the default information hint of the way is generally not very good).
Gossip less say, first of all use:
1, first import the necessary two JS files

2. Write the form code that needs to be validated and write the verification code (there are two ways to write the verification code, first use the normal way)

//adding custom validation rulesJQuery.validator.addMethod (' editor ',function () {    returneditorcontent.hascontents ();});//when using, directly in the verification condition inside Editor:true prompt content is also editor: "Prompt content"//#formId为需要进行验证的表单ID$ ("FormId"). Validate ({errorelement:"Div",//tag error with "div" tag, default: "Label"Wrapper: "Li",//use the "Li" tab and wrap up the top errorelement.Errorclass: "Validate-error",//error prompt CSS class name "error"OnSubmittrue,//whether the commit is validation, default: TrueOnfocusout:true,//whether to validate when the focus is taken, default: TrueOnKeyUptrue,//whether to verify when tapping the keyboard, default: TrueOnClickfalse,//whether to validate on mouse click (General validation Checkbox,radiobox)Focuscleanup:false,//When the element that is not validated is focusable, and the error is removed    //validation rulesrules: {loginName: {//input box that needs to be validated nameRequiredtrue //verification Condition: Required}, Loginpassword: {//input box that needs to be validated nameRequiredtrue,//verification Condition: RequiredMinlength:5//validation Condition: Minimum length of 5}, Email: {//input box that needs to be validated nameRequiredtrue,//verification Condition: RequiredEmailtrue //validation criteria: Format for email        }    },    //Verify that the prompt message was not passedmessages: {loginName: {required:"User name is not allowed to be empty!"//Verify that a message was not passed}, Loginpassword: {required:"Password is not allowed to be empty!", Minlength:jQuery.format ("Password Enter at least {0} characters!")}, Email: {Required:"Email is not allowed to be empty", Email:"Bad mail address format!"        }    },    //Show Validation ErrorsShowErrors:function(Errormap, Errorarr) {//errormap {' name ': ' Error message '}        //Errorarr [{' Message ': ' Error message ', element: ({})}]Alert (errorarr[0].message); //Get Focus$ (errorarr[0].element). focus (); },})

Built-in authentication method:

Required () return: Boolean Required validation Element

Required (Dependency-expression) return: A Boolean required element depends on the result of an expression

Required (Dependency-callback) return: The Boolean required element depends on the result of the callback function

Remote (URL) return: Boolean Request for a remoting check. A URL is usually a remote call method

MinLength (length) return: Boolean set Minimum length

MaxLength (length) return: Boolean Set maximum length

Rangelength (range) returns: Boolean sets a length range [Min,max]

Min (value) returns: Boolean sets the maximum value

Max (value) returns: Boolean sets the minimum value

Email () Return: Boolean authentication e-mail format

Range (Range) returns: Boolean set value ranges

URL () Return: Boolean Authentication URL format

Date () return: Boolean validates date format (similar to 30/30/2008 format, does not verify date accuracy only validates format)

Dateiso () return: Boolean to verify the date format of the ISO type

Datede () return: Boolean-validated German-style date format (29.04.1994 or 1.1.2006)

Number () returns: Boolean to validate decimal digits (including decimals)

Digits () return: Boolean validation integer

CreditCard () return: Boolean Authentication credit card number

Accept (extension) returns: Boolean string that validates the same suffix name

Equalto (Other) returns: Boolean verifies that the contents of the two input boxes are the same

Phoneus () return: Boolean to verify American phone numbers

Options for Validate ():
Debug: Debug mode (Form not submitted): $ (". Selector"). Validate
({
Debug:true
})
Set Debug as Default: $.validator.setdefaults ({
Debug:true
})
Submithandler:
A function that is run after validation is added to the form-submitted function, otherwise the form will not submit $ (". Selector"). Validate ({
Submithandler: function (form) {

$ (form). Ajaxsubmit ();
}
})
Ignore:
Do not validate for some elements $ ("#myform"). Validate ({
Ignore: ". Ignore"
})
rules:
In the form of a custom rule, key:value, key is the element to be validated, and value can be a string or an object $ (". Selector"). Validate ({
rules:{
Name: "Required",
email:{
Required:true,
Email:true
}
}
})
Messages:
Custom hint information Key:value form key is the element to validate, the value is a string or a function of $ (". Selector"). Validate ({
rules:{
Name: "Required",
email:{
Required:true,
Email:true
}
},
Messages:{
Name: "Name cannot be empty",
email:{
Required: "e-mail cannot be empty",
Email: "E-mail address is not correct"
}
}
})
groups:
Validation of a set of elements, with an error prompt, using Errorplacement to control where the error message is placed $ ("#myform"). 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);
},
Debug:true
})
Onubmit

Boolean type default: True
Whether to validate $ (". Selector") when committing. Validate ({
onsubmit: false
})
Onfocusout

Boolean Default: True
Whether to validate $ (". Selector") when the focus is taken. Validate ({
Onfocusout: false
})
onkeyupBoolean Default: True
Whether to validate $ (". Selector") when tapping on the keyboard. Validate ({
onkeyup: false
})
onclickBoolean Default: True
Whether to validate (general authentication Checkbox,radiobox) $ (". Selector") on mouse click. Validate ({
onclick: false
})
FocusinvalidBoolean Default: True
After a form is submitted, a form that does not pass validation (the first one or the failed validation form that has received the focus before submission) gets the focus $ (". Selector"). Validate ({
Focusinvalid: false
})
FocuscleanupBoolean Default: False
When the element that is not validated is focusable, and the error prompt is removed (avoid and focusinvalid.) $ (". Selector"). Validate ({
Focuscleanup: True
})
ErrorclassString default: "Error"
Specify the CSS class name for the error prompt, and you can customize the style of the error hint $ (". Selector"). Validate ({
Errorclass: "Invalid"
})
errorelementString default: "Label"
What tags are used to mark the error $ (". Selector"). Validate
errorelement: "Em"
})
wrapperString
What label to use and then wrap the top errorelement up $ (". Selector"). Validate ({
wrapper: "Li"
})
ErrorlabelcontainerSelector
Unify the error information in a container $ ("#myform"). Validate ({
Errorlabelcontainer: "#messageBox",
wrapper: "Li",
Submithandler: function () {alert ("submitted!")}
})

showerrors:
With a function, you can display the total number of elements that have not been validated by $ (". Selector"). Validate ({
showerrors: function (errormap,errorlist) {
$ ("#summary"). HTML ("Your form contains" + this.numberofinvalids () + "Errors,see details below.");
This.defaultshowerrors ();
}
})
errorplacement:
With a function, you can customize where the error is placed $ ("#myform"). Validate ({
errorplacement: function (error,element) {
Error.appendto (Element.parent ("TD"). Next ("TD"));
},
Debug:true

})
Success:
The element to be validated passes the validated action, if followed by a string, as a CSS class, or with a function of $ ("#myform"). Validate ({
success: "Valid",
Submithandler:function () {alert ("submitted!")}
})
Highlight
You can add effects, flicker, and so on to elements that do not pass validation.


Addmethod (Name,method,message) method:
Parameter name is the name of the method added
The parameter method is a function that receives three parameters (Value,element,param) value is the element's values, element is the elements themselves param is a parameter, we can use Addmethod to add built-in Validation The methods

External validation methods such as a field, can only lose one letter, the range is a-f, the following:

$.validator.addmethod ("AF",function(value,element,params) {  if(value.length>1 ) {   returnfalse;  }   if (Value>=params[0] && value<=params[1]) {   returntrue;  } Else {   returnfalse;  },"must be a letter, and a-f");


Id= "username" in a form field, write in rules
username:{
Af:["A", "F"]
}

The first parameter of the Addmethod is the name of the added validation method, which is the AF
The third parameter of Addmethod is the custom error prompt, where the prompt is: "must be a letter, and A-f"
The second parameter of the Addmethod is a function, which is more important and determines how to use this verification method.
If there is only one parameter, write directly, if AF: "A", then A is the only parameter, if multiple parameters, used in [], separated by commas

jquery Validate Plugin Usage tips

Related Article

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.