jquery.validate使用详解
一、简单应用实例:
1.用class样式进行验证,用法简单,但不能自定义错误信息,只能修改jquery-1.4.1.min.js中的内置消息,也不支持高级验证规则。
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
|
< script type = "text/javascript" language = "javascript" src = "http://www.jb51.net/Scripts/jquery-1.4.1.min.js" ></ script > < script type = "text/javascript" language = "javascript" src = "http://www.jb51.net/Scripts/jquery.validate.min.js" ></ script > < h2 >ValidateTest</ h2 > < form id = "loginForm" action = "post" > < table border = "0" cellpadding = "0" cellspacing = "0" > < tr > < td > < input type = "text" id = "UserEmail" class = "required email" /></ td > </ tr > < tr > < td > < input type = "password" id = "Password" class = "required" /></ td > </ tr > < tr > < td > < input type = "submit" value = "submit" onclick = "checkInput();" /> </ td > </ tr > </ table > </ form > < script language = "javascript" type = "text/javascript" > function checkInput() { if ($("#loginForm").valid()) { return true; } return false; } </ script > |
当然,如果不希望使用onclick事件进行提交验证,也可以在页面加载时加上jQuery的监控,代码如下:
1
2
3
|
$(document).ready( function () { jQuery( "#loginForm" ).validate(); }); |
这时就不需要在提交按钮上加 onclick="checkInput();"这个事件了。
2.使用Json字符串验证,使用该规则验证,必须额外引入jquery.metadata.pack.js文件
修改上面的两个INPUT如下:
1
2
|
< input type = "text" id = "UserEmail" class = "{validate:{ required:true,email:true }}" /> < input type = "password" id = "Password" class = "{validate:{required:true,minlength:6,messages:{required:'请输入密码 ',minlength:'密码至少6位'}}}" /> |
可以看到,我们已经可以自定义错误消息了。
另外必须在页面中加上以下代码:
1
2
3
4
5
|
$(document).ready( function () { $( "#loginForm" ).validate({ meta: "validate" }); }); |
二、验证规则的应用
1.使用class验证的规则:
在class中可以使用:required,email,number,url,date,dateISO,dateDE,digits,creditcard,phoneUS
可以增加属性:minlength,maxlength,min,max,accept,remote(注:请检查是否返回是bool还是xml),equalTo='#password'
没有找到使用办法的内置方法:required(dependency-expression),required(dependency-callback),range,rangelength
2.使用Json对象验证的规则:
在class中进行如下定义:class=“{validate:{required:true,minlength:6,messages:{required:'请输入密码',minlength:'密码太短啦至少6位'}}}”
我们仍可进行以下定义:number:true, email:true, url:true, date:true, dateISO:true, dateDE:true, digits:true, creditcard:true, phoneUS:true
min:3, max:10, minlength:3, maxlength:10,required: '#other:checked'【此处表达式函数为required(dependency-expression)】
相比使用class来说,我们已经可以使用range方法了,可定义为数字range:[3,10],字符串长度rangelength:[3,10],remote:url,accept:'.csv|.jpg|.doc|.docx', equalTo:'#Password'
没有找到使用方法的内置方法:required(dependency-callback)
三、高级验证方法
在前面说到的简单验证中,使用起来非常简单,有些傻瓜式的味道,但毕竟有些内置规则不能使用。但要想做到灵活运用,还是需要通过JS编码来完成。这样不但所有的内置规则可以使用,而且我们还可以自定义验证规则。以下实例我从易到难逐个列出:
1.编写JS的简单方法
仍以登录验证为例:
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
< script type = "text/javascript" language = "javascript" src = "http://www.jb51.net/Scripts/jquery-1.4.1.min.js" ></ script > < script type = "text/javascript" language = "javascript" src = "http://www.jb51.net/Scripts/jquery.validate.min.js" ></ script > < h2 >Validate-High</ h2 > < form action = "" id = "loginForm" method = "post" > < table border = "0" cellpadding = "0" cellspacing = "0" > < tr > < td > < input type = "text" id = "UserEmail" /> </ td > </ tr > < tr > < td > < input type = "password" id = "Password" /> </ td > </ tr > < tr > < td > < input type = "submit" value = "submit" /> </ td > </ tr > </ table > </ form > < script language = "javascript" type = "text/javascript" > $(document).ready(function () { var validateOpts = { rules: { UserEmail: { required: true, email: true }, Password: { required: true } }, messages: { UserEmail: { required: "请输入邮箱地址", email: "邮箱地址不正确" }, Password: { required: "请输入密码" } } }; $("#loginForm").validate(validateOpts); }); </ script > |
我们只需设置validate的参数即可。
2.equalTo的使用,一般在注册时会用到
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
< script type = "text/javascript" language = "javascript" src = "http://www.jb51.net/Scripts/jquery-1.4.1.min.js" ></ script > < script type = "text/javascript" language = "javascript" src = "http://www.jb51.net/Scripts/jquery.validate.min.js" ></ script > < h2 >ValidateHigh</ h2 > < form action = "" id = "loginForm" method = "post" > < table border = "0" cellpadding = "0" cellspacing = "0" > < tr > < td > < input type = "text" id = "UserEmail" /> </ td > </ tr > < tr > < td > < input type = "password" id = "Password" /> </ td > </ tr > < tr > < td > < input type = "password" id = "RePassword" /> </ td > </ tr > < tr > < td > < input type = "submit" value = "submit" /> </ td > </ tr > </ table > </ form > < script language = "javascript" type = "text/javascript" > $(document).ready(function () { var validateOpts = { rules: { UserEmail: { required: true, email: true }, Password: { required: true }, RePassword: { equalTo: "#Password" } }, messages: { UserEmail: { required: "请输入邮箱地址", email: "邮箱地址不正确" }, Password: { required: "请输入密码" }, RePassword: { equalTo: "两次输入密码必须相同" } } }; $("#loginForm").validate(validateOpts); }); </ script > |
3.required(dependency-callback)的使用,绿色字体。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
var validateOpts = { rules: { age: { required: true , min: 3 }, parent: { required: function (element) { return $( "#age" ).val() < 13; } } } } |
4.自定义规则,使用addMethod方法,如下:
//方法接收三个参数(value,element,param)
//value是元素的值,element是元素本身 param是参数,我们可以用addMethod来添加除built-in Validation methods之外的验证方法
//比如有一个字段,只能输一个字母,范围是a-f,写法如下
1
2
3
4
5
6
7
8
9
10
|
$.validator.addMethod( "af" , function (value, element, params) { if (value.length >1) { returnfalse; } if (value >=params[0] && value <=params[1]) { returntrue; } else { returnfalse; } }, "必须是一个字母,且a-f" ); |
这样我们就可以在rules中加上这个规则,如下
1
2
3
4
5
6
7
|
var validateOpts = { rules: { selectorId: { af: [ "a" , "f" ] //如果只有一个参数,直接写,如果af:"a",那么a就是这个唯一的参数,如果多个参数,用在[]里,用逗号分开 } } } |
另外,经过试验,在Json方式中,我们可以使用af:['a','f'],这个验证可以起作用,在class方式中,在某个元素上增加af='af',验证也可以起到作用。
5.ajax验证,使用remote
1
2
3
4
5
|
remote: { url: "CheckEmail" , type: "post" , dataType: "json" } |
如果我们验证的方法是返回Boolean类型,这个方法是没有问题的。但很多时候我们可能返回的信息会更多,或者返回其它类型,这时我们可以重新定义一个新的remote方法,示例如下(返回一个Json对象):
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
$.validator.addMethod( "jsonremome" , function (value, element, param) { if ( this .optional(element)) return "dependency-mismatch" ; var previous = this .previousValue(element); if (! this .settings.messages[element.name]) this .settings.messages[element.name] = {}; previous.originalMessage = this .settings.messages[element.name].remote; this .settings.messages[element.name].remote = previous.message; param = typeof param == "string" && { url: param} || param; if (previous.old !== value) { previous.old = value; var validator = this ; this .startRequest(element); var data = {}; data[element.name] = value; $.ajax($.extend( true , { url: param, mode: "abort" , port: "validate" + element.name, dataType: "json" , data: data, success: function (response) { validator.settings.messages[element.name].remote = previous.originalMessage; //var valid = response === true; var valid = response.Result === true ; if (valid) { var submitted = validator.formSubmitted; validator.prepareElement(element); validator.formSubmitted = submitted; validator.successList.push(element); validator.showErrors(); } else { var errors = {}; //var message = (response.Message || validator.defaultMessage(element, "jsonremote")); var message = response.Message || "远程验证未通过" ; errors[element.name] = $.isFunction(message) ? message(value) : message; validator.showErrors(errors); } previous.valid = valid; validator.stopRequest(element, valid); } }, param)); return "pending" ; } elseif ( this .pending[element.name]) { return "pending" ; } return previous.valid; }); |
服务器端方法如下(MVC中):
1
2
3
4
|
public JsonResult CheckEmail( string UserEmail) { returnnew JsonResult { Data = new { Result = false , Message= "Please change the filed" } }; } |
我们就可以使用jsonremote来取代remote方法了。当然,remote方法依然可以使用。
6.错误显示规则
1
2
3
4
5
6
|
var validateOpts = { wrapper: "div" , // default has no wrapper errorClass: "invalid" , // the default value is error errorElement: "em" , // default value is lable errorLabelContainer: "#messageBox" , // to gather all the error messages } |
以上就是本文的全部内容,希望能给大家一个参考,也希望大家多多支持脚本之家。
来源:http://www.jb51.net/article/85701.htm