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", // 需要忽略不验证的字段,可以自己写selector
ignoreTitle: false, // 不使用表单元素的title当提示信息
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有三类方法:

  1. $.validator静态方法

    1
    2
    >    $.validator.format('请输入至少{0}个字符');
    >
  1. $('选择器').validate()返回的$.validator实例方法

    1
    2
    3
    >    var validator = $('form').validate();
    > validator.form();
    >
  1. 插件的方法

    1
    2
    3
    4
    >    $().validate();
    > $().valid();
    > $().rules();
    >

自定义的选择器

插件扩展了selector选择器。

  • :blink
  • :filled
  • :unchecked

Validator实例的方法

Validator实例的公共方法。

form()

触发校验.

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');
}

resetForm()

1
2
var formValidator = $('form').validate();
formValidator.resetForm();

showErrors(errors)

errorsObject类型, 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
// value: 元素值
// element:元素本身
// params:元素规则
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}"));

$.validator.format( template, argument, argumentN… )

1
2
3
var template = jQuery.validator.format("{0} is not a valid value");
// later, results in 'abc 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
// boolean
$( "#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
// alias required to cRequired with new message
$.validator.addMethod("cRequired", $.validator.methods.required,
"Customer name required");
// alias minlength, too
$.validator.addMethod("cMinlength", $.validator.methods.minlength,
// leverage parameter replacement for minlength, {0} gets replaced with 2
$.validator.format("Customer name must have at least {0} characters"));
// combine them both, including the parameter for minlength
$.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).

当用户在一个已经验证为validfield中输入任何东西,在field失去焦点时被验证(onfoucsout)。

normalizer

normalizer: 是非常有用的一个方法,因为form中的组件,不可能全是原生的组件,所以提供这个方法,用来返回组件的值。

注意:

  1. normalizer:不能改变组件的值,只能把改变后的值,给validator进行校验。
  2. 参数value,是validator内部获取element的值,在使用第三方组件时,很可能不正确
  3. this时当前被校验的DOMelement
  4. 返回值必须时一个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
// 全局的normalizer和local的normalizer同时使用
$( "#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;
}
}
}
} );