jQuery Validate
jQuery Validate
The jQuery Validate plug-in provides powerful validation functions for forms, making client-side form validation easier and 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 provides an API for writing user-defined methods. All bundled methods use English for error messages by default and have been translated into 37 other languages.
This plugin is written and maintained by Jörn Zaefferer, a member of the jQuery team, a lead developer on the jQuery UI team, and the maintainer of QUnit. This plugin has been around since the early days of jQuery in 2006 and has been updated ever since. The current version is 1.14.0.
Visit jQuery Validate official website and download the latest version of jQuery Validate plug-in.
Default verification rules
Serial number | Rules | Description |
---|---|---|
1 | required:true | Required field. |
2 | remote:"check.php" | Use the ajax method to call check.php to verify the input value. |
3 | email:true | Must enter a correctly formatted email. |
4 | url:true | You must enter the URL in the correct format. |
5 | date:true | The date must be entered in the correct format. Date verification ie6 error, use with caution. |
6 | dateISO:true | The date (ISO) in the correct format must be entered, for example: 2009-06-23, 1998/01/ twenty two. Only the format is verified, not the validity. |
7 | number:true | Must enter a legal number (negative number, decimal). |
8 | digits:true | Must enter an integer. |
9 | creditcard: | Must enter a legal credit card number. |
10 | equalTo:"#field" | The input value must be the same as #field. |
11 | accept: | Enter a string with a legal suffix (the suffix 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] | The input length must be 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 prompt
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 prompt package, which is located in dist/localization/messages_zh.js of the download package. The content is as follows:
(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 localize the message The file dist/localization/messages_zh.js is introduced to the page:
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
Usage method
1. Write the verification rules into the control
Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script> <script> $.validator.setDefaults({ submitHandler: function() { alert("提交事件!"); } }); $().ready(function() { $("#commentForm").validate(); }); </script> <style> .error{ color:red; } </style> </head> <body> <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> </body> </html>
Run instance»
Click the "Run instance" button to view the online instance
2. Write the verification rules to the js code At
$().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: "请选择两个主题" }});
messages, if a control does not have a message, the default message
instance
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script> <script> $.validator.setDefaults({ submitHandler: function() { alert("提交事件!"); } }); $().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: "请选择两个主题" } }); }); </script> <style> .error{ color:red; } </style> </head> <body> <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" style="display:none">至少选择两个</label> </fieldset> <p> <input class="submit" type="submit" value="提交"> </p> </fieldset> </form> </body> </html>
will be called to run Instance»
Click the "Run Instance" button to view the online instance
required: true value is required.
required: "#aa:checked" If the value of the expression is true, verification is required.
required: function(){} Returns true, indicating that verification is required.
The latter two are commonly used for elements in the form that need to be filled in or left out at the same time.
Common methods and issues to note
1. Use other methods to replace the default SUBMIT
$().ready(function() { $("#signupForm").validate({ submitHandler:function(form){ alert("提交事件!"); form.submit(); } });});
Use ajax method
$(".selector").validate({ submitHandler: function(form) { $(form).ajaxSubmit(); } })
You can set the default value of validate. The writing is as follows:
$.validator.setDefaults({ submitHandler: function(form) { alert("提交事件!");form.submit(); }});
If you want to submit the form, you need to use form.submit() instead of $(form).submit().
2. Debug, only verify and not submit the form
If this parameter is true, then the form will not be submitted and only checked, which is very convenient for debugging.
$().ready(function() { $("#signupForm").validate({ debug:true });});
If there are multiple forms on a page that you want to set as debug, use:
$.validator.setDefaults({ debug: true})
3, ignore: ignore certain elements and do not verify
ignore: ".ignore"
4, Change the position where the error message is displayed
errorPlacement:Callback
Indicate the position where the error is placed. The default is: error.appendTo(element.parent()); that is, the error message is placed behind the verified element.
errorPlacement: function(error, element) { error.appendTo(element.parent()); }
Instance
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script> <script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script> <script> $.validator.setDefaults({ submitHandler: function() { alert("提交事件!"); } }); $().ready(function() { // 提交时验证表单 var validator = $("#form1").validate({ errorPlacement: function(error, element) { // Append error within linked label $( element ) .closest( "form" ) .find( "label[for='" + element.attr( "id" ) + "']" ) .append( error ); }, errorElement: "span", messages: { user: { required: " (必需字段)", minlength: " (不能少于 3 个字母)" }, password: { required: " (必需字段)", minlength: " (字母不能少于 5 个且不能大于 12 个)", maxlength: " (字母不能少于 5 个且不能大于 12 个)" } } }); $(".cancel").click(function() { validator.resetForm(); }); }); </script> <style> .error{ color:red; } </style> </head> <body> <form method="get" class="cmxform" id="form1" action=""> <fieldset> <legend>登录框</legend> <p> <label for="user">用户名</label> <input id="user" name="user" required minlength="3"> </p> <p> <label for="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> </body> </html>
Run Instance»
Click the "Run Instance" button to view the online instance
The function of the code is: generally, the error message is displayed in <td class="status"></td>, if it is radio, it is displayed in <td></td>, If it is a checkbox, it is displayed behind the content.
Parameters | Type | Description | Default value |
---|---|---|---|
String | Specifies the css class name of the error prompt, and you can customize the style of the error prompt. | "error" | |
String | What label should be used to mark errors? The default is label, which can be changed to em. | "label" | |
Selector | Display or hide the verification information, which can automatically realize when an error message appears. The container properties become displayed and hidden when there are no errors, which is of little use. | errorContainer: "#messageBox1, #messageBox2" | |
Selector | Put the error message Put them uniformly in a container. | ||
String | What label should be used to wrap the errorELement above. |
Trigger method | Type | Description | Default value |
---|---|---|---|
onsubmit | Boolean | Validate on submission. Set to false to use other methods to verify. | true |
onfocusout | Boolean | Validate when focus is lost (excluding checkboxes/radio buttons). | true |
onkeyup | Boolean | Validate on keyup. | true |
onclick | Boolean | Validates on click of checkboxes and radio buttons. | true |
focusInvalid | Boolean | After submitting the form, the form that failed validation (the first one or obtained before submission The focused (unvalidated) form will gain focus. | true |
focusCleanup | Boolean | If true then remove errors when an element that fails validation gets focus hint. Avoid using it with focusInvalid. | false |
// 重置表单$().ready(function() { var validator = $("#signupForm").validate({ submitHandler:function(form){ alert("submitted"); form.submit(); } }); $("#reset").click(function() { validator.resetForm(); });});
8. Asynchronous verification
remote:URL
Use ajax for verification. By default, the current verified value will be 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 no other output.
9. Add custom verification
addMethod:name, method, message
Custom verification 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: To add or Add in jquery.validate.js file. It is recommended to write it in the additional-methods.js file.
Note: Add: isZipCode: "can only include Chinese characters, English letters, numbers and underlines" in the messages_cn.js file. Add a reference to the additional-methods.js file before calling.
10. Verification of radio, checkbox, and select
The required of radio means that 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"/>
The required in checkbox means it must be selected.
<input type="checkbox" class="checkbox" id="agree" name="agree" required />
The minlength of checkbox represents the minimum number that must be selected, maxlength represents the maximum number of selections, and rangelength:[2,3] represents the range of 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[]" />
select's required indicates that 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>
select's minlength represents the minimum number of selected items (multi-selectable select), maxlength represents the maximum selected number, and rangelength:[2,3] represents the selected number interval.
<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 the verification is passed. |
rules() | Options | Returns the validation rules of the element. |
rules("add",rules) | Options | Add verification rules. |
rules("remove",rules) | Options | Remove validation rules. |
removeAttrs(attributes) | Options | Remove special attributes and return them. |
Custom Selector | ||
:blank | Validator | Filter with no value. |
:filled | Array <Element> | Filter with value. |
:unchecked | Array <Element> | Filter for unselected elements. |
Utilities | ||
String | Replace {n} in the template with parameters. |
Name | Return type | Description |
---|---|---|
form() | Boolean | Verify whether the form returns success or failure. |
element(element) | Boolean | Verifies whether a single element succeeds or fails. |
resetForm() | undefined | Restore the previously verified FORM to its original state before verification. |
showErrors(errors) | undefined | Show specific error messages. |
Validator function | ||
setDefaults(defaults) | undefined | Change the default settings. |
addMethod(name,method,message) | undefined | Add a new verification method. Must include a unique name, a JAVASCRIPT method and a default message. |
addClassRules(name,rules) | undefined | Add a combined verification type, which is more useful when using multiple verification methods in a class. |
addClassRules(rules) | undefined | Add a combined verification type, which is more useful when using multiple verification methods in a class. This is to add multiple verification methods at the same time. |
Built-in verification method
Name | Return type | Description |
---|---|---|
required () | Boolean | Required validation element. |
required(dependency-expression) | Boolean | Required elements depend on the result of expression. |
required(dependency-callback) | Boolean | Required elements depend on the result of the callback function. |
remote(url) | Boolean | Request remote verification. url is usually a remote call 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 | Verify the email format. |
range(range) | Boolean | Set the range of values. |
url() | Boolean | Verify URL format. |
date() | Boolean | Verify the date format (similar to the format of 30/30/2008, the date accuracy is not verified, only the format is verified) . |
dateISO() | Boolean | Verify the ISO type date format. |
dateDE() | Boolean | Verifies the German date format (29.04.1994 or 1.1.2006). |
number() | Boolean | Validate decimal numbers (including decimals). |
digits() | Boolean | Validate integers. |
creditcard() | Boolean | Verify credit card number. |
accept(extension) | Boolean | Verify strings with the same suffix name. |
equalTo(other) | Boolean | Verify whether the contents of the two input boxes are the same. |
phoneUS() | Boolean | Verify the US phone number. |
validate() options
Code | |
---|---|