jQuery Validation使用总结
注意:表单元素必须含有name
属性,不然jQuery validation
不工作。
options配置
jQuery.validator.defaults
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 { debug : false , messages: {}, groups: {}, rules: {}, errorClass: "error" , pendingClass: "pending" , validClass: "valid" , errorElement: "label" , focusCleanup: false , focusInvalid: true , errorContainer: $( [] ), errorLabelContainer: $( [] ), onsubmit: true , ignore: ":hidden" , ignoreTitle: false , onfocusin: function ( element ) { }, onfocusout: function ( element ) { }, onkeyup: function ( element, event ) { }, onclick: function ( element ) { }, highlight: function ( element, errorClass, validClass ) { }, unhighlight: function ( element, errorClass, validClass ) { } }
方法
jQuery.validator
有三类方法:
$.validator
的静态方法
1 2 > $.validator.format('请输入至少{0}个字符' ); >
$('选择器').validate()
返回的$.validator
实例方法
1 2 3 > var validator = $('form' ).validate(); > validator.form(); >
插件的方法
1 2 3 4 > $().validate(); > $().valid(); > $().rules(); >
自定义的选择器
插件扩展了selector
选择器。
:blink
:filled
:unchecked
Validator
实例的方法
Validator
实例的公共方法。
触发校验.
1 2 3 4 5 var formValidator = $('form' ).validate();if (formValidator.form()) { console .log('valid form' ); }
element(element)
校验单个表单元素
1 2 3 4 var formValidator = $('form' ).validate();if (formValidator.element('#startDate' )){ console .log('valid element' ); }
1 2 var formValidator = $('form' ).validate();formValidator.resetForm();
showErrors(errors)
errors
是Object
类型, key
是表单元素的name
属性,value
是要显示的消息
1 2 3 4 var formValidator = $('form' ).validate();formValidator.showErrors({ firstName: '请输入名字' });
numberOfInvalids([errors])
返回校验不通过的元素个数
1 2 3 4 5 var validator = $( "#myform" ).validate({ invalidHandler: function ( ) { $( "#summary" ).text( validator.numberOfInvalids() + " field(s) are invalid" ); } });
destory()
销毁Validator
实例
1 2 var validator = $( "#myform" ).validate();validator.destroy();
Validator
的静态方法$.validator.addMethod( name, method [, message ] ) 1 2 3 4 5 6 jQuery.validator.addMethod("math" , function (value, element, params ) { return this .optional(element) || value == params[0 ] + params[1 ]; }, jQuery.validator.format("Please enter the correct value for {0} + {1}" ));
1 2 3 var template = jQuery.validator.format("{0} is not a valid value" );alert(template("abc" ));
$.validator.setDefaults(options)
options参考validate(options)
重置全局validator
配置
1 2 3 jQuery.validator.setDefaults({ debug: true });
$.validator.addClassRules()
添加校验规则。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 jQuery.validator.addClassRules("name" , { required: true , minlength: 2 }); jQuery.validator.addClassRules({ name: { required: true , minlength: 2 }, zip: { required: true , digits: true , minlength: 5 , maxlength: 5 } });
Validator
内置的方法required
适用: input, select, checkbox, radio
1 2 3 4 required(); required(selector); required(callback);
input
1 2 3 4 5 6 <form id ="myform" > <label for ="field" > Required: </label > <input type ="text" class ="left" id ="field" name ="field" > <br /> <input type ="submit" value ="Validate!" > </form >
1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true } } });
Select
1 2 3 4 5 6 7 8 9 10 11 <form id ="myform" > <label for ="fruit" > Please select a fruit</label > <select id ="fruit" name ="fruit" title ="Please select something!" > <option value ="" > Select...</option > <option value ="1" > Banana</option > <option value ="2" > Apple</option > <option value ="3" > Peach</option > </select > <br /> <input type ="submit" value ="Validate!" > </form >
1 2 3 4 5 6 7 $( "#myform" ).validate({ rules: { fruit: { required: true } } });
radio
1 2 3 4 5 6 7 8 9 10 11 12 13 <form id ="myform" > <label for ="gender_male" > <input type ="radio" id ="gender_male" value ="m" name ="gender" /> Male </label > <label for ="gender_female" > <input type ="radio" id ="gender_female" value ="f" name ="gender" /> Female </label > <label for ="gender" class ="error" > Please select your gender</label > <br /> <input type ="submit" value ="Validate!" > </form >
1 2 3 4 5 6 7 $( "#myform" ).validate({ rules: { gender: { required: true } } });
checkbox
1 2 3 4 5 6 <form id ="myform" > <label for ="agree" > Please agree to our policy</label > <input type ="checkbox" id ="agree" title ="Please agree to our policy!" name ="agree" /> <br /> <input type ="submit" value ="Validate!" > </form >
1 2 3 4 5 6 7 $( "#myform" ).validate({ rules: { agree: { required: true } } });
依赖其它元素(dependence-expression)
1 2 3 4 5 6 7 8 <form id ="myform" > <label for ="other" > Check to make next field required</label > <input id ="other" type ="checkbox" > <br > <input id ="details" name ="details" > <br > <input type ="submit" value ="Validate!" > </form >
1 2 3 4 5 6 7 $( "#myform" ).validate({ rules: { details: { required: "#other:checked" } } });
function
1 2 3 4 5 6 7 8 9 <form id ="myform" > <label > Age </label > <input id ="age" name ="age" > <br > <label > Parent </label > <input id ="parent" name ="parent" > <br > <input type ="submit" value ="Validate!" > </form >
1 2 3 4 5 6 7 8 9 10 11 12 13 $( "#myform" ).validate({ rules: { age: { required: true , min: 3 }, parent: { required: function (element ) { return $("#age" ).val() < 13 ; } } } });
minlength(length) 1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , minlength: 3 } } });
maxlength(length) 1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , maxlength: 4 } } });
ranglength(Array) 1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , rangelength: [2 , 6 ] } } });
min(value) 1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , min: 13 } } });
max(value) 1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , max: 13 } } });
range( range ) 1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , range: [13 , 23 ] } } });
step( value )
输入的数字是step的倍数
1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , step: 10 } } });
email 1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , email: true } } });
url 1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , url: true } } });
number 1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , number: true } } });
digits 1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , digits: true } } });
equalTo(Selector) 1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { password: "required" , password_again: { equalTo: "#password" } } });
dateISO
字段是合法时间,非格式。
适用:input
1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , dateISO: true } } });
additional-methods
包含在additional-methods.js
accept(mimetype)
校验文件后缀
适用:<input type="file">
1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , accept: "audio/*" } } });
creditcard()
校验信用卡号
1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , creditcard: true } } });
phoneUS
可以参考实现电话校验
1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , phoneUS: true } } });
require_from_group
一组至少填写几个。
1 2 3 4 5 6 7 8 9 10 11 12 <form id ="myform" > <label for ="mobile_phone" > Mobile phone: </label > <input class ="left phone-group" id ="mobile_phone" name ="mobile_phone" > <br /> <label for ="home_phone" > Home phone: </label > <input class ="left phone-group" id ="home_phone" name ="home_phone" > <br /> <label for ="work_phone" > Work phone: </label > <input class ="left phone-group" id ="work_phone" name ="work_phone" > <br /> <input type ="submit" value ="Validate!" > </form >
1 2 3 4 5 6 7 8 9 10 11 12 13 $( "#myform" ).validate({ rules: { mobile_phone: { require_from_group: [1 , ".phone-group" ] }, home_phone: { require_from_group: [1 , ".phone-group" ] }, work_phone: { require_from_group: [1 , ".phone-group" ] } } });
extension( [extension ] )
参数:string
默认值: png|jpe?g|gif
适用:<input>
1 2 3 4 5 6 7 8 $( "#myform" ).validate({ rules: { field: { required: true , extension: "xls|csv" } } });
重构规则(组合规则)
重构规则,可以把多个规则组合起来,一起使用。
1 2 3 4 5 6 7 8 9 $.validator.addMethod("cRequired" , $.validator.methods.required, "Customer name required" ); $.validator.addMethod("cMinlength" , $.validator.methods.minlength, $.validator.format("Customer name must have at least {0} characters" )); $.validator.addClassRules("customer" , { cRequired : true , cMinlength : 2 });
错误消息
错误消息有四种提供方式: options, data-*, element title, default messages
错误消息的优先级:options > element title属性 > default messages
可以使用统一消息 ,也可以指定具体的规则消息
1 2 <input required data-msg ="Please fill this field" > <input data-rule-minlength ="2" data-rule-maxlength ="4" data-msg-minlength ="At least two chars" data-msg-maxlength ="At most fours chars" >
跳过验证提交
添加formnovalidate
属性。
1 <input type ="submit" formnovalidate name ="cancel" value ="Cancel" >
验证事件
默认情况下,form
在用户点击submit
按钮,或者input
获得焦点时,按下enter
键。
另外,如果一个field
已经高亮并且invalid
,当用户输入任何东西,它都会被验证(使用onkeyup).
当用户在一个已经验证为valid
的field
中输入任何东西,在field
失去焦点时被验证(onfoucsout)。
normalizer
normalizer
: 是非常有用的一个方法,因为form
中的组件,不可能全是原生的组件,所以提供这个方法,用来返回组件的值。
注意:
normalizer:不能改变组件的值,只能把改变后的值,给validator
进行校验。
参数value,是validator
内部获取element
的值,在使用第三方组件时,很可能不正确
this
时当前被校验的DOMelement
返回值必须时一个string 类型
1 2 3 4 5 6 7 8 9 10 $( "#myform" ).validate( { rules: { field: { required: true , normalizer: function ( value ) { return dayjs($(this ).datepicker('getDate' )).format('YYYY-MM-DD' ); } } } } );
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 $( "#myform" ).validate( { normalizer: function ( value ) { return $.trim( value ); }, rules: { username: { required: true }, url_input: { required: true , url: true , normalizer: function ( value ) { var url = value; return 'https://' + url; } } } } );