最近在做一个用户注册登录的页面,资料查寻过程中发现了一个非常不错的客户端验证的极品-jQuery.validate。
它是著名的JavaScript包jQuery的一个插件,其实它还有其它的一些插件应该都爽,有待慢慢来学习
官方地址:http://bassistance.de/jquery-plugins/jquery-plugin-validation/
jQuery用户手册:http://jquery.org.cn/visual/cn/index.xml
开发使用起来非常简单明了,
我的代码:
2 .
3 . /* 设置默认属性 */
4 . $.validator.setDefaults({
5 . submitHandler: function (form) { form.submit(); }
6 . });
7 . // 中文字两个字节
8 . jQuery.validator.addMethod( " byteRangeLength " , function (value, element, param) {
9 . var length = value.length;
10 . for ( var i = 0 ; i < value.length; i ++ ){
11 . if (value.charCodeAt(i) > 127 ){
12 . length ++ ;
13 . }
14 . }
15 . return this .optional(element) || ( length >= param[ 0 ] && length <= param[ 1 ] );
16 . }, " 请确保输入的值在3-15个字节之间(一个中文字算2个字节) " );
17 .
18 . /* 追加自定义验证方法 */
19 . // 身份证号码验证
20 . jQuery.validator.addMethod( " isIdCardNo " , function (value, element) {
21 . return this .optional(element) || isIdCardNo(value);
22 . }, " 请正确输入您的身份证号码 " );
23 .
24 . // 字符验证
25 . jQuery.validator.addMethod( " userName " , function (value, element) {
26 . return this .optional(element) || /^ [\u0391 - \uFFE5\w] + $ / .test(value);
27 . }, " 用户名只能包括中文字、英文字母、数字和下划线 " );
28 .
29 . // 手机号码验证
30 . jQuery.validator.addMethod( " isMobile " , function (value, element) {
31 . var length = value.length;
32 . return this .optional(element) || (length == 11 && /^ ((( 13 [ 0 - 9 ]{ 1 }) | ( 15 [ 0 - 9 ]{ 1 })) + \d{ 8 })$ / .test(value));
33 . }, " 请正确填写您的手机号码 " );
34 .
35 . // 电话号码验证
36 . jQuery.validator.addMethod( " isPhone " , function (value, element) {
37 . var tel = /^ (\d{ 3 , 4 } -? ) ? \d{ 7 , 9 }$ / g;
38 . return this .optional(element) || (tel.test(value));
39 . }, " 请正确填写您的电话号码 " );
40 .
41 . // 邮政编码验证
42 . jQuery.validator.addMethod( " isZipCode " , function (value, element) {
43 . var tel = /^ [ 0 - 9 ]{ 6 }$ / ;
44 . return this .optional(element) || (tel.test(value));
45 . }, " 请正确填写您的邮政编码 " );
46 . $(regFrom).validate({
47 . /* 设置验证规则 */
48 . rules: {
49 . userName: {
50 . required: true ,
51 . userName: true ,
52 . byteRangeLength: [ 3 , 15 ]
53 . },
54 . password: {
55 . required: true ,
56 . minLength: 5
57 . },
58 . repassword: {
59 . required: true ,
60 . minLength: 5 ,
61 . equalTo: " #password "
62 . },
63 . question: {
64 . required: true
65 . },
66 . answer: {
67 . required: true
68 . },
69 . realName: {
70 . required: true
71 . },
72 . cardNumber: {
73 . isIdCardNo: true
74 . },
75 . mobilePhone: {
76 . isMobile: true
77 . },
78 . phone: {
79 . isPhone: true
80 . },
81 . email: {
82 . required: true ,
83 . email: true
84 . },
85 . zipCode: {
86 . isZipCode: true
87 . }
88 . },
89 . /* 设置错误信息 */
90 . messages: {
91 . userName: {
92 . required: " 请填写用户名 " ,
93 . byteRangeLength: " 用户名必须在3-15个字符之间(一个中文字算2个字符) "
94 . },
95 . password: {
96 . required: " 请填写密码 " ,
97 . minlength: jQuery.format( " 输入{0}. " )
98 . },
99 . repassword: {
100 . required: " 请填写确认密码 " ,
101 . equalTo: " 两次密码输入不相同 "
102 . },
103 . question: {
104 . required: " 请填写您的密码提示问题 "
105 . },
106 . answer: {
107 . required: " 请填写您的密码提示答案 "
108 . },
109 . realName: {
110 . required: " 请填写您的真实姓名 "
111 . },
112 . email: {
113 . required: " 请输入一个Email地址 " ,
114 . email: " 请输入一个有效的Email地址 "
115 . }
116 . },
117 . /* 错误信息的显示位置 */
118 . errorPlacement: function (error, element) {
119 . error.appendTo( element.parent() );
120 . },
121 . /* 验证通过时的处理 */
122 . success: function (label) {
123 . // set as text for IE
124 . label.html( " " ).addClass( " checked " );
125 . },
126 . /* 获得焦点时不验证 */
127 . focusInvalid: false ,
128 . onkeyup: false
129 . });
130 .
131 . // 输入框获得焦点时,样式设置
132 . $('input').focus( function (){
133 . if ($( this ).is( " :text " ) || $( this ).is( " :password " ))
134 . $( this ).addClass('focus');
135 . if ($( this ).hasClass('have_tooltip')) {
136 . $( this ).parent().parent().removeClass('field_normal').addClass('field_focus');
137 . }
138 . });
139 .
140 . // 输入框失去焦点时,样式设置
141 . $('input').blur( function () {
142 . $( this ).removeClass('focus');
143 . if ($( this ).hasClass('have_tooltip')) {
144 . $( this ).parent().parent().removeClass('field_focus').addClass('field_normal');
145 . }
146 . });
147 . });
网上的资料有人说,它跟prototype包会有冲突,我还没有同时使用过,这点不是很清楚,但我是发现一个问题:
对于最小/大 长度的验证方法,作者可能考虑到大家的命名习惯不同,同时做了minLength和minlength(maxLength和maxlength)方法, 应该哪一个都是可以的,但对于用户Message来说,只能够定义针对minlength(maxlength),才能调用用户自定义的Message,
否则只是调用包的默认Message,但具体原因还没有查清楚。同时,这个插件提供了本地化的消息,但对于我这里初学者来说,怎么使用它还有待摸索!
----------------------------------------------华丽的分割线---------------------------------------------------------------
jQuery.validate中内置的验证方法
1、 required() 返回:Bool //必填验证元素2、 required(dependency-expression) 返回:Bool //必填元素依赖于表达式的结果
3、 required(dependency-callback) 返回:Boolean // 必填元素依赖于回调函数的结果
4、 remote(url) 返回:Bool //请求远程校验。url通常是一个远程调用方法
5、 minlength(length) 返回:Bool //设置最小长度
6、 maxlength(length) 返回:Bool // 设置最大长度
7、 rangelength(range) 返回:Bool //设置一个长度范围[min,max]
8、 min(value) 返回:Bool // 设置最大值
9、 ax(value) 返回:Bool //设置最小值
10、 email() 返回:Bool //验证电子邮箱格式
11、 range(range) 返回:Bool // 设置值的范围
12、 url() 返回:Bool // 验证URL格式
13、 date() 返回:Bool //验证日期格式(类似30/30/2008的格式,不验证日期准确性只验证格式)
14、 dateISO() 返回:Bool // 验证ISO类型的日期格式
15、 dateDE() 返回:Bool //验证德式的日期格式(29.04.1994 or 1.1.2006)
17、 number() 返回:Bool // 验证十进制数字(包括小数的)
18、 digits() 返回:Bool // 验证整数
19、 creditcard() 返回:Bool // 验证信用卡号
20、 accept(extension) 返回:Bool // 验证相同后缀名的字符串
21、 equalTo(other) 返回:Bool // 验证两个输入框的内容是否相同
22、 phoneUS() 返回:Bool //验证美式的电话号码
validate ()的可选项
1、debug:进行调试模式(表单不提交):
语法:把调试设置为默认:
$.validator.setDefaults({
debug:true
})
2、submitHandler:通过验证后运行的函数,里面要加上表单提交的函数,否则表单不会提交
语法:
$(".selector").validate({
submitHandler:function(form) {
$(form).ajaxSubmit();
}
})
3、ignore:对某些元素不进行验证
语法:
$("#myform").validate({ ignore:"ignore" })
4、rules:自定义规则,key:value的形式,key是要验证的元素,value可以是字符串或对象
语法:
$(".selector").validate({
rules:{
name:"required",
email:{
required:true,
email:true
}
}
})
5、messages:自定义的提示信息key:value的形式key是要验证的元素,值是字符串或函数
语法:
$(".selector").validate({
rules:{
name:"required",
email:{
required:true,
email:true
}
},
messages:{
name:"Name不能为空",
email:{
required:"E-mail不能为空",
email:"E-mail地址不正确"
}
}
})
6、groups:对一组元素的验证,用一个错误提示,用error Placement控制把出错信息放在哪里
语法:
$("#myform").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);
},
debug:true
})
7、Onubmit Boolean 默认:true,是否提交时验证
语法:
$(".selector").validate({
onsubmit:false
})
8、onfocusout Boolean 默认:true ,是否在获取焦点时验证
语法:
$(".selector").validate({
onfocusout:false
})
9、onkeyup Boolean 默认:true ,是否在敲击键盘时验证
语法:
$(".selector").validate({
onkeyup:false
})
10、onclick Boolean 默认:true,是否在鼠标点击时验证(一般验证checkbox,radiobox)
语法:
$(".selector").validate({
onclick:false
})
11、focusInvalid Boolean 默认:true,提交表单后,未通过验证的表单(第一个或提交之前获得焦点的未通过验证的表单)会获得焦点
语法:
$(".selector").validate({
focusInvalid:false
})
12、focusCleanup Boolean 默认:false,当未通过验证的元素获得焦点时,并移除错误提示(避免和 focusInvalid.一起使用)
语法:
$(".selector").validate({
focusCleanup:true
})
13、errorClass String 默认:"error",指定错误提示的css类名,可以自定义错误提示的样式
语法:
$(".selector").validate({
errorClass:"invalid"
})
14、errorElement String 默认:"label",使用什么标签标记错误
语法:
$(".selector").validate({
errorElement:"em"
})
15、wrapper String:使用什么标签再把上边的errorELement包起来
语法:
$(".selector").validate({
wrapper:"li"
})
16、errorLabelContainer Selector:把错误信息统一放在一个容器里面
语法:
$("#myform").validate({
errorLabelContainer:"#messageBox",
wrapper:"li",
submitHandler:function() { alert("Submitted!") }
})
17、showErrors:跟一个函数,可以显示总共有多少个未通过验证的元素
语法:
$(".selector").validate({
showErrors:function(errorMap,errorList) {
$("#summary").html("Your form contains " + this.numberOfInvalids() + " errors,see details below.");
this.defaultShowErrors();
}
})
18、errorPlacement:跟一个函数,可以自定义错误放到哪里
语法:
$("#myform").validate({
errorPlacement:function(error,element) { error.appendTo(element.parent("td").next("td"));},
debug:true
})
19、success:要验证的元素通过验证后的动作,如果跟一个字符串,会当做一个css类,也可跟一个函数
语法:
$("#myform").validate({
success:"valid",
submitHandler:function() { alert("Submitted!") }
})
20、highlight:可以给未通过验证的元素加效果,闪烁等
21、addMethod(name,method,message)方法
参数name是添加的方法的名字
参数method是一个函数,接收三个参数(value,element,param) value是元素的值,element是元素本身 param是参数,我们可以用addMethod来添加除built-in Validation methods之外的验证方法 比如有一个字段,只能输一个字母,范围是a-f,写法如下:
$.validator.addMethod("af",function(value,element,params){ if(value.length>1){ return false; } if(value>=params[0] && value<=params[1]){ return true; } else{ return false; } },"必须是一个字母,且a-f");
用的时候,比如有个表单字段的id="username",则在rules中写
username:{ af:["a","f"] }
addMethod的第一个参数,就是添加的验证方法的名子,这时是af
addMethod的第三个参数,就是自定义的错误提示,这里的提示为:"必须是一个字母,且a-f"
addMethod的第二个参数,是一个函数,这个比较重要,决定了用这个验证方法时的写法;
如果只有一个参数,直接写,如果af:"a",那么a就是这个唯一的参数,如果多个参数,用在[]里,用逗号分开;
对于动态提交表单时submitHandler是比较好用的,用户可以在submit时的onclick事件中进行验证,如:
$("input[type='submit']").click(function(){ $("form1").validate({ submitHandler: function(form) { //这里就可以处理ajax事件 $.ajax(function(){ //处理 }); } });