jQuery Validate
The jQuery Validate plugin provides powerful validation functionality for forms, making client-side form validation simpler while providing a large number of customization options to meet various application needs. The plugin bundles a set of useful validation methods, including URL and email validation, and also provides an API for writing user-defined methods. All bundled methods use English as the error message by default, and have been translated into 37 other languages.
This plugin was written and maintained by Jörn Zaefferer, a member of the jQuery team, a lead developer of the jQuery UI team, and the maintainer of QUnit. The plugin first appeared in the early days of jQuery in 2006 and has been updated ever since. The current version is1.14.0。
Visitthe jQuery Validate official websiteto download the latest version of the jQuery Validate plugin.
Import the js library (using the CDN provided by ByteDance)
<script src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/1.12.3/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/localization/messages_zh.min.js"></script>
Default validation rules
| No. | Rule | Description |
|---|---|---|
| 1 | required:true | The field is required. |
| 2 | remote:"check.php" | Use the ajax method to call check.php to validate the input value. |
| 3 | email:true | Must enter an email in the correct format. |
| 4 | url:true | Must enter a URL in the correct format. |
| 5 | date:true | Must enter a date in the correct format. Date validation fails in IE6; use with caution. |
| 6 | dateISO:true | Must enter a date in the correct ISO format, for example: 2009-06-23, 1998/01/22. Only validates the format, not the validity. |
| 7 | number:true | Must enter a valid number (negative numbers, decimals). |
| 8 | digits:true | Must enter an integer. |
| 9 | creditcard: | Must enter a valid credit card number. |
| 10 | equalTo:"#field" | The input value must be the same as #field. |
| 11 | accept: | Must enter a string with a valid extension name (the extension of the uploaded file). |
| 12 | maxlength:5 | Enter a string with a maximum length of 5 (Chinese characters count as one character). |
| 13 | minlength:10 | Enter a string with a minimum length of 10 (Chinese characters count as one character). |
| 14 | rangelength:[5,10] | Enter a string with a length between 5 and 10 (Chinese characters count as one character). |
| 15 | range:[5,10] | The input value must be between 5 and 10. |
| 16 | max:5 | The input value cannot be greater than 5. |
| 17 | min:10 | The input value cannot be less than 10. |
Default messages
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 ).",
number: "Please enter a valid number.",
digits: "Please enter only digits.",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
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 less than or equal to {0}." ),
min: $.validator.format( "Please enter a value greater than or equal to {0}." )
}
jQuery Validate provides a Chinese message package, located at dist/localization/messages_zh.js in the download package, with the following content:
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
define( ["jquery", "../jquery.validate"], factory );
} else {
factory( jQuery );
}
}(function( $ ) {
/*
* Translated default messages for the jQuery validation plugin.
* Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語)
*/
$.extend($.validator.messages, {
required: "这是必填字段",
remote: "请修正此字段",
email: "请输入有效的电子邮件地址",
url: "请输入有效的网址",
date: "请输入有效的日期",
dateISO: "请输入有效的日期 (YYYY-MM-DD)",
number: "请输入有效的数字",
digits: "只能输入数字",
creditcard: "请输入有效的信用卡号码",
equalTo: "你的输入不相同",
extension: "请输入有效的后缀",
maxlength: $.validator.format("最多可以输入 {0} 个字符"),
minlength: $.validator.format("最少要输入 {0} 个字符"),
rangelength: $.validator.format("请输入长度在 {0} 到 {1} 之间的字符串"),
range: $.validator.format("请输入范围在 {0} 到 {1} 之间的数值"),
max: $.validator.format("请输入不大于 {0} 的数值"),
min: $.validator.format("请输入不小于 {0} 的数值")
});
}));
You can include this localization message file, dist/localization/messages_zh.js, into the page:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/localization/messages_zh.min.js"></script>
Usage
1. Write the validation rules into the control
<script src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/1.12.3/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/localization/messages_zh.min.js"></script> <script> $.validator.setDefaults({ submitHandler: function() { alert("提交事件!"); } }); $().ready(function() { $("#commentForm").validate(); }); </script> <form class="cmxform" id="commentForm" method="get" action=""> <fieldset> <legend>输入您的名字,邮箱,URL,备注。</legend> <p> <label for="cname">Name (必需, 最小两个字母)</label> <input id="cname" name="name" minlength="2" type="text" required> </p> <p> <label for="cemail">E-Mail (必需)</label> <input id="cemail" type="email" name="email" required> </p> <p> <label for="curl">URL (可选)</label> <input id="curl" type="url" name="url"> </p> <p> <label for="ccomment">备注 (必需)</label> <textarea id="ccomment" name="comment" required></textarea> </p> <p> <input class="submit" type="submit" value="Submit"> </p> </fieldset> </form>
2. Write the validation rules into the JS code
$().ready(function() {
// 在键盘按下并释放及提交后验证提交表单
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "请输入您的名字",
lastname: "请输入您的姓氏",
username: {
required: "请输入用户名",
minlength: "用户名必需由两个字符组成"
},
password: {
required: "请输入密码",
minlength: "密码长度不能小于 5 个字符"
},
confirm_password: {
required: "请输入密码",
minlength: "密码长度不能小于 5 个字符",
equalTo: "两次密码输入不一致"
},
email: "请输入一个正确的邮箱",
agree: "请接受我们的声明",
topic: "请选择两个主题"
}
})
});
For the messages part, if a control has no message, the default message will be used.
<form class="cmxform" id="signupForm" method="get" action="">
<fieldset>
<legend>验证完整的表单</legend>
<p>
<label for="firstname">名字</label>
<input id="firstname" name="firstname" type="text">
</p>
<p>
<label for="lastname">姓氏</label>
<input id="lastname" name="lastname" type="text">
</p>
<p>
<label for="username">用户名</label>
<input id="username" name="username" type="text">
</p>
<p>
<label for="password">密码</label>
<input id="password" name="password" type="password">
</p>
<p>
<label for="confirm_password">验证密码</label>
<input id="confirm_password" name="confirm_password" type="password">
</p>
<p>
<label for="email">Email</label>
<input id="email" name="email" type="email">
</p>
<p>
<label for="agree">请同意我们的声明</label>
<input type="checkbox" class="checkbox" id="agree" name="agree">
</p>
<p>
<label for="newsletter">我乐意接收新信息</label>
<input type="checkbox" class="checkbox" id="newsletter" name="newsletter">
</p>
<fieldset id="newsletter_topics">
<legend>主题 (至少选择两个) - 注意:如果没有勾选“我乐意接收新信息”以下选项会隐藏,但我们这里作为演示让它可见</legend>
<label for="topic_marketflash">
<input type="checkbox" id="topic_marketflash" value="marketflash" name="topic">Marketflash
</label>
<label for="topic_fuzz">
<input type="checkbox" id="topic_fuzz" value="fuzz" name="topic">Latest fuzz
</label>
<label for="topic_digester">
<input type="checkbox" id="topic_digester" value="digester" name="topic">Mailing list digester
</label>
<label for="topic" class="error">Please select at least two topics you'd like to receive.</label>
</fieldset>
<p>
<input class="submit" type="submit" value="提交">
</p>
</fieldset>
</form>
required: trueThe value is required.
required: "#aa:checked"If the expression is true, validation is required.
required: function(){}If it returns true, validation is required.
The latter two are commonly used for elements in a form that need to be filled in or left empty together.
Common methods and things to note
1. Use other ways to replace the default SUBMIT
$().ready(function() {
$("#signupForm").validate({
submitHandler:function(form){
alert("提交事件!");
form.submit();
}
});
});
Use the ajax approach
$(".selector").validate({
submitHandler: function(form)
{
$(form).ajaxSubmit();
}
})
You can set the default values for validate, as follows:
$.validator.setDefaults({
submitHandler: function(form) { alert("提交事件!");form.submit(); }
});
If you want to submit the form, you need to use form.submit(), not $(form).submit().
2. debug, only validate and do not submit the form
If this parameter is true, the form will not be submitted; only validation is performed, which is very convenient for debugging.
$().ready(function() {
$("#signupForm").validate({
debug:true
});
});
If there are multiple forms on a page that all want to be set to debug, use:
$.validator.setDefaults({
debug: true
})
3. ignore: ignore certain elements without validation
ignore: ".ignore"
4. Change the position where error messages are displayed
errorPlacement:Callback
Specify the position where errors are placed. The default is: error.appendTo(element.parent()); that is, the error message is placed after the element being validated.
errorPlacement: function(error, element) {
error.appendTo(element.parent());
}
Example
<p>将错误信息放在 label 元素后并使用 span 元素包裹它</p>
<form method="get" class="cmxform" id="form1" action="">
<fieldset>
<legend>Login Form</legend>
<p>
<label for="user">Username</label>
<input id="user" name="user" required minlength="3">
</p>
<p>
<label for="password">Password</label>
<input id="password" type="password" maxlength="12" name="password" required minlength="5">
</p>
<p>
<input class="submit" type="submit" value="Login">
</p>
</fieldset>
</form>
The code's purpose is: normally, the error message is displayed in <td class="status"></td>; if it is a radio, it is displayed in <td></td>; if it is a checkbox, it is displayed after the content.
| Parameter | Type | Description | Default value |
|---|---|---|---|
| errorClass | String | Specify the CSS class name for error messages; you can customize the style of error messages. | "error" |
| errorElement | String | The tag used to mark errors; the default is label, and it can be changed to em. | "label" |
| errorContainer | Selector | Show or hide validation information. It can automatically change the container attribute to display when an error message appears and hide it when there is no error; it is of little use. errorContainer: "#messageBox1, #messageBox2" |
|
| errorLabelContainer | Selector | Put all error messages together in one container. | |
| wrapper | String | Use which tag to wrap the above errorElement. |
Generally these three attributes are used together to display all error messages in one container, and automatically hide when there is no message.
errorContainer: "div.error",
errorLabelContainer: $("#signupForm div.error"),
wrapper: "li"
5. Change the style of error message display
Set the style of error messages; icons can be added to the display. In this system, a validation.css has been created specifically for maintaining the styles of validation files.
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. Execute a function after each field passes validation
success:String,Callback
The action after an element to be validated passes validation. If a string is provided, it will be treated as a CSS class; a function can also be provided.
success: function(label) {
// set as text for IE
label.html(" ").addClass("checked");
//label.addClass("valid").text("Ok!")
}
Add "valid" to the validated element, and define the style in CSS as <style>label.valid {}</style>.
success: "valid"
7. Modify the trigger method of validation
The following are of boolean type, but it is recommended not to add them casually unless you need to change them to false.
| Trigger method | Type | Description | Default value |
|---|---|---|---|
| onsubmit | Boolean | Validate on submit. Set to false to use other methods for validation. | true |
| onfocusout | Boolean | Validate on blur (excluding checkboxes/radio buttons). | true |
| onkeyup | Boolean | Validate on keyup. | true |
| onclick | Boolean | Validate when clicking checkboxes and radio buttons. | true |
| focusInvalid | Boolean | After submitting the form, the form that fails validation (the first one or the invalid form that gained focus before submission) will receive focus. | true |
| focusCleanup | Boolean | If true, when an element that fails validation gains focus, the error message is removed. Avoid using it together with focusInvalid. | false |
// 重置表单
$().ready(function() {
var validator = $("#signupForm").validate({
submitHandler:function(form){
alert("submitted");
form.submit();
}
});
$("#reset").click(function() {
validator.resetForm();
});
});
8. Asynchronous validation
remote:URL
Use ajax for validation. By default, the currently validated value is submitted to the remote address. If you need to submit other values, you can use the data option.
remote: "check-email.php"
remote: {
url: "check-email.php", //后台处理程序
type: "post", //数据发送方式
dataType: "json", //接受数据格式
data: { //要传递的数据
username: function() {
return $("#username").val();
}
}
}
The remote address can only output "true" or "false", and cannot have any other output.
9. Add custom validation
addMethod:name, method, message
Custom validation method
// 中文字两个字节
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("请确保输入的值在{0}-{1}个字节之间(一个中文字算2个字节)"));
// 邮政编码验证
jQuery.validator.addMethod("isZipCode", function(value, element) {
var tel = /^[0-9]{6}$/;
return this.optional(element) || (tel.test(value));
}, "请正确填写您的邮政编码");
Note: It should be added in the additional-methods.js file or in the jquery.validate.js file. It is recommended to generally write it in the additional-methods.js file.
Note: Add it in the messages_cn.js file: isZipCode: "can only include Chinese characters, English letters, numbers and underscores". Before calling, add a reference to the additional-methods.js file.
10. Validation of radio, checkbox, and select
For radio, required means one must be selected.
<input type="radio" id="gender_male" value="m" name="gender" required /> <input type="radio" id="gender_female" value="f" name="gender"/>
For checkbox, required means it must be checked.
<input type="checkbox" class="checkbox" id="agree" name="agree" required />
For checkbox, minlength indicates the minimum number of selections required, maxlength indicates the maximum number of selections, and rangelength:[2,3] indicates a range for the number of selections.
<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" required 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[]" />
For select, required means the selected value cannot be empty.
<select id="jungle" name="jungle" title="Please select something!" required>
<option value=""></option>
<option value="1">Buga</option>
<option value="2">Baga</option>
<option value="3">Oi</option>
</select>
For select, minlength indicates the minimum number of selected items (for multi-select selects), maxlength indicates the maximum number of selected items, and rangelength:[2,3] indicates a range for the number of selected items.
<select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, minlength:2}" multiple="multiple">
<option value="b">Banana</option>
<option value="a">Apple</option>
<option value="p">Peach</option>
<option value="t">Turtle</option>
</select>
jQuery.validate Chinese API
| Name | Return type | Description |
|---|---|---|
| validate(options) | Validator | Validate the selected form. |
| valid() | Boolean | Check whether validation passed. |
| rules() | Options | Return the validation rules for an element. |
| rules("add",rules) | Options | Add validation rules. |
| rules("remove",rules) | Options | Remove validation rules. |
| removeAttrs(attributes) | Options | Remove special attributes and return them. |
| Custom selectors | ||
| :blank | Validator | Filter for elements without a value. |
| :filled | Array <Element> | Filter for elements with a value. |
| :unchecked | Array <Element> | Filter for elements that are not selected. |
| Utility tools | ||
| jQuery.format(template,argument,argumentN...) | String | Replace {n} in the template with arguments. |
Validator
The validate method returns a Validator object. The Validator object has many methods that can be used to trigger validation or change the form content. Below are some commonly used methods.
| Name | Return type | Description |
|---|---|---|
| form() | Boolean | Validate the form and return success or failure. |
| element(element) | Boolean | Validate a single element for success or failure. |
| resetForm() | undefined | Restore the previously validated form to its original state before validation. |
| showErrors(errors) | undefined | Display a specific error message. |
| Validator functions | ||
| setDefaults(defaults) | undefined | Change default settings. |
| addMethod(name,method,message) | undefined | Add a new validation method. It must include a unique name, a JavaScript method, and a default message. |
| addClassRules(name,rules) | undefined | Add a composite validation type, useful when using multiple validation methods in one class. |
| addClassRules(rules) | undefined | Add composite validation types, useful when using multiple validation methods in one class. This one adds multiple validation methods at the same time. |
Built-in validation methods
| Name | Return type | Description |
|---|---|---|
| required() | Boolean | Required validation for an element. |
| required(dependency-expression) | Boolean | Required element depends on the result of an expression. |
| required(dependency-callback) | Boolean | Required element depends on the result of a callback function. |
| remote(url) | Boolean | Request remote validation. The url is usually a remote invocation method. |
| minlength(length) | Boolean | Set the minimum length. |
| maxlength(length) | Boolean | Set the maximum length. |
| rangelength(range) | Boolean | Set a length range [min,max]. |
| min(value) | Boolean | Set the minimum value. |
| max(value) | Boolean | Set the maximum value. |
| email() | Boolean | Validate email format. |
| range(range) | Boolean | Set a range of values. |
| url() | Boolean | Validate URL format. |
| date() | Boolean | Validate date format (e.g., 30/30/2008; only validates the format, not the accuracy of the date). |
| dateISO() | Boolean | Validate ISO date format. |
| dateDE() | Boolean | Validate German date format (29.04.1994 or 1.1.2006). |
| number() | Boolean | Validate decimal numbers (including decimals). |
| digits() | Boolean | Validate integers. |
| creditcard() | Boolean | Validate credit card numbers. |
| accept(extension) | Boolean | Validate strings with the same suffix. |
| equalTo(other) | Boolean | Validate whether the content of two input fields is the same. |
| phoneUS() | Boolean | Validate US phone numbers. |
validate() options
| Description | Code |
|---|---|
| debug: Enable debug mode (the form is not submitted). |
$(".selector").validate
({
debug:true
})
|
| Set debug as the default. |
$.validator.setDefaults({
debug:true
})
|
| submitHandler: A function that runs after validation passes. You must include the form submission function inside it, otherwise the form will not be submitted. |
$(".selector").validate({
submitHandler:function(form) {
$(form).ajaxSubmit();
}
})
|
| ignore: Skip validation for certain elements. |
$("#myform").validate({
ignore:".ignore"
})
|
| rules: Custom rules in key:value form, where key is the element to validate and value can be a string or an object. |
$(".selector").validate({
rules:{
name:"required",
email:{
required:true,
email:true
}
}
})
|
| messages: Custom messages in key:value form, where key is the element to validate and value can be a string or a function. |
$(".selector").validate({
rules:{
name:"required",
email:{
required:true,
email:true
}
},
messages:{
name:"Name不能为空",
email:{
required:"E-mail不能为空",
email:"E-mail地址不正确"
}
}
})
|
| groups: Validate a group of elements with one error message, and use 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
})
|
| OnSubmit: Type Boolean, default true. Specifies whether to validate on submit. |
$(".selector").validate({
onsubmit:false
})
|
| onfocusout: Type Boolean, default true. Specifies whether to validate when an element loses focus. |
$(".selector").validate({
onfocusout:false
})
|
| onkeyup: Type Boolean, default true. Specifies whether to validate on keyup. |
$(".selector").validate({
onkeyup:false
})
|
| onclick: Type Boolean, default true. Specifies whether to validate on mouse click (usually for checkbox and radiobox). |
$(".selector").validate({
onclick:false
})
|
| focusInvalid: Type Boolean, default true. After submitting the form, the first invalid form element (or the invalid element that had focus before submission) will receive focus. |
$(".selector").validate({
focusInvalid:false
})
|
| focusCleanup: Type Boolean, default false. When an invalid element receives focus, remove the error message (avoid using together with focusInvalid). |
$(".selector").validate({
focusCleanup:true
})
|
| errorClass: Type String, default "error". Specifies the CSS class name for error messages, allowing you to customize the style of error messages. |
$(".selector").validate({
errorClass:"invalid"
})
|
| errorElement: Type String, default "label". Specifies which tag is used to mark errors. |
$(".selector").validate
errorElement:"em"
})
|
| wrapper: Type String. Specifies which tag is used to wrap the errorElement above. |
$(".selector").validate({
wrapper:"li"
})
|
| errorLabelContainer: Type Selector. Put all error messages together in a container. |
$("#myform").validate({
errorLabelContainer:"#messageBox",
wrapper:"li",
submitHandler:function() {
alert("Submitted!")
}
})
|
| showErrors: Takes a function to display how many elements have failed validation. |
$(".selector").validate({
showErrors:function(errorMap,errorList) {
$("#summary").html("Your form contains " + this.numberOfInvalids() + " errors,see details below.");
this.defaultShowErrors();
}
})
|
| errorPlacement: Takes a function to customize where errors are placed. |
$("#myform").validate({
errorPlacement:function(error,element) {
error.appendTo(element.parent("td").next("td"));
},
debug:true
})
|
| success: The action after an element passes validation. If given a string, it is treated as a CSS class; a function can also be given. |
$("#myform").validate({
success:"valid",
submitHandler:function() {
alert("Submitted!")
}
})
|
| highlight: Can add effects, flashing, etc., to elements that fail validation. |
addMethod(name, method, message) method
The parameter name is the name of the method being added.
The parameter method is a function that receives three parameters (value, element, param).
value is the element's value, element is the element itself, and param is the parameter.
We can use addMethod to add validation methods beyond the built-in validation methods. For example, if a field can only accept one letter within the range a-f, the code is as follows:
$.validator.addMethod("af",function(value,element,params){
if(value.length>1){
return false;
}
if(value>=params[0] && value<=params[1]){
return true;
}else{
return false;
}
},"必须是一个字母,且a-f");
If a form field has name="username", then in rules write:
username:{
af:["a","f"]
}
The first parameter of addMethod is the name of the added validation method; here it is af.
The third parameter of addMethod is the custom error message; here the message is: "must be a letter and within a-f".
The second parameter of addMethod is a function; it is quite important and determines how this validation method is used.
If there is only one parameter, write it directly, e.g., af:"a", where a is the only parameter. If there are multiple parameters, write them in [] separated by commas.
meta String approach
$("#myform").validate({
meta:"validate",
submitHandler:function() {
alert("Submitted!") }
})
<script type="text/javascript"
src="js/jquery.metadata.js.html"></script>
<script type="text/javascript"
src="js/jquery.validate.js.html"></script>
<form id="myform">
<input type="text"
name="email" class="{validate:{ required:true,email:true }}" />
<input type="submit"
value="Submit" />
</form>