Home >Web Front-end >JS Tutorial >Detailed example of jQuery form validation plug-in validate_jquery
The validate plug-in is a form validation plug-in based on jquery. There are many commonly used verification methods that we can call directly. Let’s take a look at the details.
Example, html code
<!DOCTYPE html> <html lang="en"> <head> <include file="Common/Header" /> <meta charset="utf-8"> <script src="/jquery.min.js"></script> </head> <body> <form class="form-horizontal" id="form" onsubmit="return false;"> <input type="text" name="password_old" class="form-control required" id="password_old" maxlength="20"> <input type="password" name="pay_password" class="form-control required" id="pay_password"> <input type="password" name="password_Repeat" class="form-control required" id="password_Repeat"> <button type="submit" id="submit" class="btn btn-success btn-padding-lr-30 margin-right-15">确定</button> </form> </body> <!-------------------------------------------------------------------------> <script src="jquery.validate.min.js"></script> <script src="messages_cn.js"></script> <script type="text/javascript"> $(document).ready(function(){ //提交 $('#submit').click(function(){ var pay_password = $('#pay_password').val(); var password_Repeat = $('#password_Repeat').val(); var password_old = $('#password_old').val(); var data = { 'pay_password':pay_password, 'password_Repeat':password_Repeat, 'password_old':password_old }; console.info(data); var v = $('#form').validate({ rules : { pay_password : { required : true, minlength : 6, ismypassword : true }, password_Repeat : { required : true, minlength : 6, ismypassword : true }, password_old : { required : true, minlength : 6, } }, messages : { pay_password : { required : "请输入密码", minlength : "字符长度不能小于6个字符", ismypassword : "密码必须由数字、英文字母和特殊字符(!,.@#$%^&*?_~)组成" }, password_Repeat : { required : "请输入密码", minlength : "字符长度不能小于6个字符", ismypassword : "密码必须由数字、英文字母和特殊字符(!,.@#$%^&*?_~)组成" }, password_old : { required : "请输入密码", minlength : "字符长度不能小于6个字符", }, } }); if(pay_password != password_Repeat){ alert("密码不一致,请重新输入确认!");return false; } //--------------------------------- if(!v.form())return false; $.ajax({ url:'{:U("Merchant/ajax_pw")}', data: data, beforeSend:function(){ }, success:function(res){ if(res == 1){ alert("密码修改成功"); } if(res == 0){ alert("两次密码一样,未做修改"); } if(res != 0 && res != 1){ alert(res); } } }); //------------------------ }); }) </script> </html>
messages_cn.js file is as follows
jQuery.extend(jQuery.validator.messages, { required: "必选字段", remote: "请修正该字段", email: "请输入正确格式的电子邮件", url: "请输入合法的网址", date: "请输入合法的日期", dateISO: "请输入合法的日期 (ISO).", number: "请输入合法的数字", digits: "只能输入整数", creditcard: "请输入合法的信用卡号", equalTo: "请再次输入相同的值", accept: "请输入拥有合法后缀名的字符串", maxlength: jQuery.validator.format("请输入一个 长度最多是 {0} 的字符串"), minlength: jQuery.validator.format("请输入一个 长度最少是 {0} 的字符串"), rangelength: jQuery.validator.format("请输入 一个长度介于 {0} 和 {1} 之间的字符串"), range: jQuery.validator.format("请输入一个介于 {0} 和 {1} 之间的值"), max: jQuery.validator.format("请输入一个最大为{0} 的值"), min: jQuery.validator.format("请输入一个最小为{0} 的值") });
Detailed explanation about the validator plug-in
Mainly divided into several parts
Basic usage of jquery.validate
jquery.validate API Description
jquery.validate custom
jquery.validate Common types of validation codes
Download address
Document address of jquery.validate plug-in
http://docs.jquery.com/Plugins/Validation
Home page of jquery.validate plug-in
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Demo provided on the jquery.validate plugin homepage
http://jquery.bassistance.de/validate/demo/
Validation Rules
The following are the default verification rules, you can also customize the rules
(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 You must enter an email in the correct format
(4)url:true You must enter the URL in the correct format
(5)date:true You must enter the date in the correct format
(6)dateISO:true You must enter the date (ISO) in the correct format, for example: 2009-06-23, 1998/01/22 Only the format is verified, not the validity
(7)number:true You must enter a legal number (negative number, decimal)
(8)digits:true must enter an integer
(9)creditcard: A legal credit card number must be entered
(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 a string 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
Verification prompt
The following is the default verification prompt. The official website has a simplified Chinese version of the verification prompt for download, or you can customize the error prompt message through jQuery.extend(jQuery.validator.messages to unify the website's verification prompt text into one file.
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.", 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 less than or equal to {0}."), min: $.validator.format("Please enter a value greater than or equal to {0}.")
How to use
1:
Use default validation rules in controls, example:
Email (required)
<input id="email" class="required email" value="email@" />
2:
You can customize validation rules in the control, example:
Customized (required, [3,5])
<input id="complex" value="hi" class="{required:true,minlength:3, maxlength:5, messages:{required:'为什么不输入一点文字呢',minlength:'输入的太少了',maxlength:'输入那么多干嘛'}}" />
3:
Customize verification rules through javascript. The following JS customizes two rules, password and confirm_password
$().ready(function() { $("#form2").validate({ rules: { password: { required: true, minlength: 5 }, confirm_password: { required: true, minlength: 5, equalTo: "#password" } }, messages: { password: { required: "没有填写密码", minlength: jQuery.format("密码不能小于{0}个字符") }, confirm_password: { required: "没有确认密码", minlength: "确认密码不能小于{0}个字符", equalTo: "两次输入密码不一致嘛" } } }); });
required can also use expressions or functions, such as
$("#form2").validate({ rules: { funcvalidate: { required: function() {return $("#password").val()!=""; } } }, messages: { funcvalidate: { required: "有密码的情况下必填" } } });
Html
密码<input id="password" name="password" type="password" /> 确认密码<input id="confirm_password" name="confirm_password" type="password" /> 条件验证<input id="funcvalidate" name="funcvalidate" value="" />
4:
Use meta to customize verification information
First set meta with JS
$("#form3").validate({ meta: "validate" });
Html
email<input class="{validate:{required:true, email:true, messages:{required:'输入email地址', email:'你输入的不是有效的邮件地址'}}}"/>
5:
Use meta to write validation rules in custom tags, such as validate
JS setting meta
$().ready(function() { $.metadata.setType("attr", "validate"); $("#form1").validate(); });
Html
<input id="email" name="email" validate="{required:true, email:true, messages:{required:'输入email地址', email:'你输入的不是有效的邮件地址'}}" />
6:
Custom validation rules
For complex validation, you can add custom validation rules through jQuery.validator.addMethod
The additional-methods.js provided by the official website contains some commonly used verification methods, such as lettersonly, ziprange, nowhitespace, etc.
Example
// 字符验证 jQuery.validator.addMethod("userName", function(value, element) { return this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value); }, "用户名只能包括中文字、英文字母、数字和下划线"); //然后就可以使用这个规则了 $("#form1").validate({ // 验证规则 rules: { userName: { required: true, userName: true, rangelength: [5,10] } }, /* 设置错误信息 */ messages: { userName: { required: "请填写用户名", rangelength: "用户名必须在5-10个字符之间" } }, });
7:
The verification methods for radio, checkbox, and select are similar
radio verification
Gender
<span> 男<input type="radio" id="gender_male" value="m" name="gender" class="{required:true}"/><br /> 女<input type="radio" id="gender_female" value="f" name="gender" /> </span>
Checkbox verification
Choose at least two items
<span> 选项1<input type="checkbox" id="check_1" value="1" name="checkGroup" class="{required:true,minlength:2, messages:{required:'必须选择',minlength:'至少选择2项'}}" /><br /> 选项2<input type="checkbox" id="check_2" value="2" name="checkGroup" /><br /> 选项3<input type="checkbox" id="check_3" value="3" name="checkGroup" /><br /> </span>
Select verification
Drop-down box
<span> <select id="selectbox" name="selectbox" class="{required:true}"> <option value=""></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </span>
8:
Ajax validation
Using remote for Ajax verification
remote: { url: "url", //url地址 type: "post", //发送方式 dataType: "json", //数据格式 data: { //要传递的数据 username: function() { return $("#username").val(); }} }
Plugin methods
Name Type
validate( options ) Returns: Validator
验证所选的FORM
valid( ) Returns: Boolean
检查是否验证通过
rules( ) Returns: Options
返回元素的验证规则
rules( "add", rules ) Returns: Options
增加验证规则
rules( "remove", rules ) Returns: Options
删除验证规则
removeAttrs( attributes ) Returns: Options
删除特殊属性并且返回他们
Custom selectors
Name Type
:blank Returns: Array cbd130a6998a818057c3a15187d5c580
没有值的筛选器
:filled Returns: Array cbd130a6998a818057c3a15187d5c580
有值的筛选器
:unchecked Returns: Array cbd130a6998a818057c3a15187d5c580
没选择的元素的筛选器
Utilities
Name Type
jQuery.format( template, argument , argumentN... ) Returns: String
用参数代替模板中的 {n}。
Validator
validate方法返回一个Validator对象, 它有很多方法, 让你能使用引发校验程序或者改变form的内容.
下面只是列出常用的.
form( ) Returns: Boolean
验证form返回成功还是失败
element( element ) Returns: Boolean
验证单个元素是成功还是失败
resetForm( ) Returns: undefined
把前面验证的FORM恢复到验证前原来的状态
showErrors( errors ) Returns: undefined
显示特定的错误信息
built-in Validation methods
Name Type
setDefaults( defaults ) Returns: undefined
改变默认的设置
addMethod( name, method, message ) Returns: undefined
添加一个新的验证方法. 必须包括名字,一个JAVASCRIPT方法和一个默认的信息
addClassRules( name, rules ) Returns: undefined
增加组合验证类型
addClassRules( rules ) Returns: undefined
增加组合验证类型
built-in Validation methods
Name Type
required( ) Returns: Boolean
必填验证元素
required( dependency-expression ) Returns: Boolean
必填元素依赖于表达式的结果.
required( dependency-callback ) Returns: Boolean
必填元素依赖于回调函数的结果.
remote( url ) Returns: Boolean
请求远程校验。url通常是一个远程调用方法
minlength( length ) Returns: Boolean
设置最小长度
maxlength( length ) Returns: Boolean
设置最大长度
rangelength( range ) Returns: Boolean
设置一个长度范围[min,max]
min( value ) Returns: Boolean
设置最小值.
max( value ) Returns: Boolean
设置最大值.
range( range ) Returns: Boolean
设置值的范围
email( ) Returns: Boolean
验证电子邮箱格式
url( ) Returns: Boolean
验证连接格式
date( ) Returns: Boolean
验证日期格式(类似30/30/2008的格式,不验证日期准确性只验证格式)
dateISO( ) Returns: Boolean
研制ISO类型的日期格式
dateDE( ) Returns: Boolean
验证德式的日期格式(29.04.1994 or 1.1.2006)
number( ) Returns: Boolean
验证十进制数字(包括小数的)
numberDE( ) Returns: Boolean
Makes the element require a decimal number with german format.
digits( ) Returns: Boolean
验证整数
creditcard( ) Returns: Boolean
验证信用卡号
accept( extension ) Returns: Boolean
验证相同后缀名的字符串
equalTo( other ) Returns: Boolean
验证两个输入框的内容是否相同
自定义jquery-validate的验证行为
1: 自定义表单提交
设置submitHandler来自定义表单提交动作
$(".selector").validate({ submitHandler: function(form) { alert("验证通过"); } });
如果需要提交表单,可以调用
form.submit(); 或者$(form).ajaxSubmit();
2: 调试模式
将debug设置为true,表单不会提交,只进行检查,方便调试
$(".selector").validate({ debug: true })
3: 设置validate的默认值
使用setDefaults可以设置validate的默认值,比如默认所有表单验证都是在debug模式下进行
$.validator.setDefaults({ debug: true })
4: 某些元素不验证
设置ignore属性可以忽略某些元素不验证
$(".selector").validate({ ignore: "ignore" })
5: 验证时机
jquery.validate可以很方便的设置在什么时候触发验证动作
onsubmit: 提交时是否验证
$(".selector").validate({ onsubmit: false })
onfocusout: 失去焦点时验证(checkboxes/radio除外)
$(".selector").validate({ onfocusout: false })
onkeyup: 在keyup时验证
$(".selector").validate({ onkeyup: false })
onclick: 在checkboxes、radio点击时验证.
$(".selector").validate({ onclick: false })
6: 重写验证规则和验证提示信息
//重写max的的验证提示信息 $.validator.messages.max = jQuery.format("Your totals musn't exceed {0}!"); //重写equal方法 $.validator.methods.equal = function(value, element, param) { return value == param; };
7: focusInvalid 是否把焦点聚焦在最后一个动作或者最近的一次出错上
$(".selector").validate({ focusInvalid: false })
8: focusCleanup
如果该属性设置为True, 那么控件获得焦点时,移除出错的class定义,隐藏错误信息,避免和 focusInvalid.一起用。
$(".selector").validate({ focusCleanup: true })
9: meta
设置meta来封装验证规则
$(".selector").validate({ meta: "validate", }) <script type="text/javascript"></script>
自定义错误消息的显示方式
默认情况下,验证提示信息用label元素来显示, 并且会添加css class, 通过css可以很方便设置出错控件以及错误信息的显示方式。
/* 输入控件验证出错*/ form input.error { border:solid 1px red;} /* 验证错误提示信息*/ form label.error{width: 200px;margin-left: 10px; color: Red;}
如果想自定义显示方式,可以修改jquery.validate的默认显示方式
默认用label显示错误消息,可以通过errorElement属性来修改
errorElement: 错误消息的html标签
$(".selector").validate errorElement: "em" })
可以在出错信息外用其他的元素包装一层。
wrapper: 错误消息的外层封装html标签
$(".selector").validate({ wrapper: "li" })
验证出错的css class默认是error,通过errorClass可以修改
errorClass: 验证出错时使用的css class
$(".selector").validate({ errorClass: "invalid" })
还自定义验证成功时的动作
success: 如果值是字符串,会当做一个css类,如果是一个函数,则执行该函数
$(".selector").validate({ success: "valid" })
或者
success: function(label) { label.html(" ").addClass("checked"); }
还可以把错误消息统一到一个容器显示
errorLabelContainer: 将错误消息统一到一个容器显示
$("#myform").validate({ errorLabelContainer: "#messageBox" })
默认情况下,错误消息是放在验证元素后面的,可以自定义错误消息的显示位置
$(".selector").validate({ errorPlacement: function(error, element) { error.appendTo( element.parent("td").next("td") ); } })
更进一步可以定义一个组,把几个地方的出错信息统一放在一个地方,用error Placement控制把出错信息放在哪里
groups:定义一个组
$(".selector").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); } })
高亮显示
highlight: 高亮显示,默认是添加errorClass
unhighlight: 和highlight对应,反高亮显示
$(".selector").validate({ highlight: function(element, errorClass) { $(element).addClass(errorClass); $(element.form).find("label[for=" + element.id + "]").addClass(errorClass); }, unhighlight: function(element, errorClass) { $(element).removeClass(errorClass); $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass); } });
或者可以完全自定义错误显示
showErrors: 得到错误的显示句柄
$(".selector").validate({ showErrors: function(errorMap, errorList) { $("#summary").html("Your form contains " + this.numberOfInvalids() + " errors, see details below."); this.defaultShowErrors(); } }) <script type="text/javascript"></script> // 手机号码验证 jQuery.validator.addMethod("mobile", function(value, element) { var length = value.length; var mobile = /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/ return this.optional(element) || (length == 11 && mobile.test(value)); }, "手机号码格式错误"); // 电话号码验证 jQuery.validator.addMethod("phone", function(value, element) { var tel = /^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/; return this.optional(element) || (tel.test(value)); }, "电话号码格式错误"); // 邮政编码验证 jQuery.validator.addMethod("zipCode", function(value, element) { var tel = /^[0-9]{6}$/; return this.optional(element) || (tel.test(value)); }, "邮政编码格式错误"); // QQ号码验证 jQuery.validator.addMethod("qq", function(value, element) { var tel = /^[1-9]\d{4,9}$/; return this.optional(element) || (tel.test(value)); }, "qq号码格式错误"); // IP地址验证 jQuery.validator.addMethod("ip", function(value, element) { var ip = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; return this.optional(element) || (ip.test(value) && (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256)); }, "Ip地址格式错误"); // 字母和数字的验证 jQuery.validator.addMethod("chrnum", function(value, element) { var chrnum = /^([a-zA-Z0-9]+)$/; return this.optional(element) || (chrnum.test(value)); }, "只能输入数字和字母(字符A-Z, a-z, 0-9)"); // 中文的验证 jQuery.validator.addMethod("chinese", function(value, element) { var chinese = /^[\u4e00-\u9fa5]+$/; return this.optional(element) || (chinese.test(value)); }, "只能输入中文"); // 下拉框验证 $.validator.addMethod("selectNone", function(value, element) { return value == "请选择"; }, "必须选择一项"); // 字节长度验证 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个字节)"));