首页 > 代码库 > jquery.validate使用攻略(表单校验)
jquery.validate使用攻略(表单校验)
目录
jquery.validate使用攻略1
第一章 jquery.validate使用攻略1
第二章 jQuery.validate.js API7
Custom selectors7
Utilities8
Validator8
List of built-in Validation methods9
validate ()的可选项11
debug:进行调试模式11
第三章 自定义jquery-validate的验证行为23
第四章 自定义错误消息的显示方式25
第五章 一些常用的验证脚本28
转自http://www.cnblogs.com/buzzlight/archive/2010/06/30/1768364.html
jquery.validate使用攻略
第一章 jquery.validate使用攻略
好几年不写JS了,资料整理起来比较慢,格式也有点乱
主要分几部分
jquery.validate 基本用法
jquery.validate API说明
jquery.validate 自定义
jquery.validate 常见类型的验证代码
下载地址
jquery.validate插件的文档地址
http://docs.jquery.com/Plugins/Validation
jquery.validate插件的主页
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
jquery.validate插件主页上提供的demo
http://jquery.bassistance.de/validate/demo/
验证规则
下面是默认校验规则,也可以自定义规则
(1)required:true 必输字段
(2)remote:"check.php" 使用ajax方法调用check.php验证输入值
(3)email:true 必须输入正确格式的电子邮件
(4)url:true 必须输入正确格式的网址
(5)date:true 必须输入正确格式的日期
(6)dateISO:true 必须输入正确格式的日期(ISO),例如:2009-06-23,1998/01/22 只验证格式,不验证有效性
(7)number:true 必须输入合法的数字(负数,小数)
(8)digits:true 必须输入整数
(9)creditcard: 必须输入合法的信用卡号
(10)equalTo:"#field" 输入值必须和#field相同
(11)accept: 输入拥有合法后缀名的字符串(上传文件的后缀)
(12)maxlength:5 输入长度最多是5的字符串(汉字算一个字符)
(13)minlength:10 输入长度最小是10的字符串(汉字算一个字符)
(14)rangelength:[5,10] 输入长度必须介于 5 和 10 之间的字符串")(汉字算一个字符)
(15)range:[5,10] 输入值必须介于 5 和 10 之间
(16)max:5 输入值不能大于5
(17)min:10 输入值不能小于10
验证提示
下面是默认的验证提示,官网有简体中文版的验证提示下载,或者通过jQuery.extend(jQuery.validator.messages自定义错误提示信息,可以将网站的验证提示文本统一到一个文件里。
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}.")
使用方式
1:
在控件中使用默认验证规则,例子:
电子邮件(必填)
<input id="email" class="required email" value="http://www.mamicode.com/email@" />
2:
可以在控件中自定义验证规则,例子:
自定义(必填,[3,5])
<input id="complex" value="http://www.mamicode.com/hi" class="{required:true,minlength:3, maxlength:5,
messages:{required:‘为什么不输入一点文字呢‘,minlength:‘输入的太少了‘,maxlength:‘输入那么多干嘛‘}}" />
3:
通过javascript自定义验证规则,下面的JS自定义了两个规则,password和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除了设置为true/false之外,还可以使用表达式或者函数,比如
$("#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:
使用meta自定义验证信息
首先用JS设置meta
$("#form3").validate({ meta: "validate" });
Html
email<input class="{validate:{required:true, email:true,
messages:{required:‘输入email地址‘, email:‘你输入的不是有效的邮件地址‘}}}"/>
5:
使用meta可以将验证规则写在自定义的标签内,比如validate
JS设置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:
自定义验证规则
对于复杂的验证,可以通过jQuery.validator.addMethod添加自定义的验证规则
官网提供的additional-methods.js里包含一些常用的验证方式,比如lettersonly,ziprange,nowhitespace等
例子
// 字符验证
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:
radio、checkbox、select的验证方式类似
radio的验证
性别
<span>
男<input type="radio" id="gender_male" value="http://www.mamicode.com/m" name="gender" class="{required:true}"/><br />
女<input type="radio" id="gender_female" value="http://www.mamicode.com/f" name="gender" />
</span>
checkbox的验证
最少选择两项
<span>
选项1<input type="checkbox" id="check_1" value="http://www.mamicode.com/1" name="checkGroup"
class="{required:true,minlength:2, messages:{required:‘必须选择‘,minlength:‘至少选择2项‘}}" /><br />
选项2<input type="checkbox" id="check_2" value="http://www.mamicode.com/2" name="checkGroup" /><br />
选项3<input type="checkbox" id="check_3" value="http://www.mamicode.com/3" name="checkGroup" /><br />
</span>
select的验证
下拉框
<span>
<select id="selectbox" name="selectbox" class="{required:true}">
<option value=""></option>
<option value="http://www.mamicode.com/1">1</option>
<option value="http://www.mamicode.com/2">2</option>
<option value="http://www.mamicode.com/3">3</option>
</select>
</span>
8:
Ajax验证
用remote可以进行Ajax验证
remote: {
url: "url", //url地址
type: "post", //发送方式
dataType: "json", //数据格式 data: { //要传递的数据
username: function() {
return $("#username").val();
}}
}
补充: jQuery Validation插件remote验证方式的Bug
http://www.cnblogs.com/JeffreyZhao/archive/2009/12/04/jquery-validate-remote-bug.html
第二章 jQuery.validate.js API
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 |
Custom selectors:
Name | Type |
:blank | Returns: Array <Element > |
没有值的筛选器 | |
:filled | Returns: Array <Element > |
有值的筛选器 | |
:unchecked | Returns: Array <Element > |
没选择的元素的筛选器 |
Utilities
Name | Type |
String utilities:
Name | Type |
jQuery.format( template, argument , argumentN... ) | Returns: String |
用参数代替模板中的 {n}。 |
Validator
validate方法返回一个Validator对象, 它有很多方法, 让你能使用引发校验程序或者改变form的内容. validator对象有很多方法, 但下面只是列出常用的.
Name | Type |
Validator methods:
Name | Type |
form( ) | Returns: Boolean |
验证form返回成功还是失败 | |
element( element ) | Returns: Boolean |
验证单个元素是成功还是失败 | |
resetForm( ) | Returns: undefined |
把前面验证的FORM恢复到验证前原来的状态 | |
showErrors( errors ) | Returns: undefined |
显示特定的错误信息 |
There are a few static methods on the validator object:
Name | Type |
Validator functions:
Name | Type |
setDefaults( defaults ) | Returns: undefined |
改变默认的设置 | |
addMethod( name, method, message ) | Returns: undefined |
添加一个新的验证方法. 必须包括一个独一无二的名字,一个JAVASCRIPT的方法和一个默认的信息 | |
addClassRules( name, rules ) | Returns: undefined |
增加组合验证类型 在一个类里面用多种验证方法里比较有用 | |
addClassRules( rules ) | Returns: undefined |
增加组合验证类型 在一个类里面用多种验证方法里比较有用,这个是一下子加多个 |
[edit ]
List of built-in Validation methods
A set of standard validation methods is provided:
Name | Type |
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 |
验证两个输入框的内容是否相同 |
Name | Type |
phoneUS( ) | Returns: Boolean |
验证美式的电话号码 |
validate ()的可选项
debug:进行调试模式
$(".selector").validate
({
debug: true
})
把调试设置为默认
$.validator.setDefaults({
debug: true
})
submitHandler:用其他方式替代默认的SUBMIT,比如用AJAX的方式提交
$(".selector").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
})
ignore:忽略某些元素不验证
$("#myform").validate({
ignore: ".ignore"
})
rules: 默认下根据form的classes, attributes, metadata判断,但也可以在validate函数里面声明
Key/value 可自定义规则. Key是对象的名字 value是对象的规则,可以组合使用 class/attribute/metadata rules.
以下代码特别验证selector类中name=‘name‘是必填项并且 email是既是必填又要符合email的格式
$(".selector").validate({
rules: {
// simple rule, converted to {required:true}
name: "required",
// compound rule
email: {
required: true,
email: true
}
}
})
messages:更改默认的提示信息
$(".selector").validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please specify your name",
email: {
required: "We need your email address to contact you",
email: "Your email address must be in the format of name@domain.com"
}
}
})
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
})
nsubmit | Boolean | Default: true |
提交时验证. 设置唯false就用其他方法去验证 | ||
· Code 不用onsubmit验证,就允许用户无论用什么方法去验证,而是提交时, 用 keyup/blur/click 等方法. $(".selector").validate({ onsubmit: false }) | ||
onfocusout | Boolean | Default: true |
Validate elements (except checkboxes/radio buttons) on blur. If nothing is entered, all rules are skipped, except when the field was already marked as invalid. | ||
· Code Disables onblur validation. $(".selector").validate({ onfocusout: false }) | ||
onkeyup | Boolean | Default: true |
在keyup时验证. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. | ||
· Code Disables onkeyup validation. $(".selector").validate({ onkeyup: false }) | ||
onclick | Boolean | Default: true |
在checkboxes 和 radio 点击时验证. | ||
· Code Disables onclick validation of checkboxes and radio buttons. $(".selector").validate({ onclick: false }) | ||
focusInvalid | Boolean | Default: true |
把焦点聚焦在最后一个动作或者最近的一次出错上via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding to steal its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off. | ||
· Code Disables focusing of invalid elements. $(".selector").validate({ focusInvalid: false }) | ||
focusCleanup | Boolean | Default: false |
如果是true那么删除出错类从出错的元素上并且隐藏出错信息当这个元素被聚焦 .避免和 focusInvalid.一起用 | ||
· Code Enables cleanup when focusing elements, removing the error class and hiding error messages when an element is focused. $(".selector").validate({ focusCleanup: true }) | ||
meta | String |
|
为了元数据使用其他插件你要包装 你的验证规则 在他们自己的项目中可以用这个特殊的选项 | ||
Tell the validation plugin to look inside a validate-property in metadata for validation rules. $("#myform").validate({ meta: "validate", submitHandler: function() { alert("Submitted!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.mamicode.com/http://code.jquery.com/jquery-latest.js"></script>
<script> $(document).ready(function(){ $("#myform").validate({ meta: "validate", submitHandler: function() { alert("Submitted!") } }) }); </script>
</head> <body> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.metadata.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <form id="myform"> <input type="text" name="email" class="{validate:{ required: true, email:true }}" /> <br/> <input type="submit" value="http://www.mamicode.com/Submit" /> </form> </body> </html> | ||
errorClass | String | Default: "error" |
创建错误类的名字为了去寻找存在的错误标签和增加它到验证失败的元素中去。 | ||
· Code Sets the error class to "invalid". $(".selector").validate({ errorClass: "invalid" }) | ||
errorElement | String | Default: "label" |
设置错误的元素,默认的是label你可以改成em.Use this element type to create error messages and to look for existing error messages. The default, "label", has the advantage of creating a meaningful link between error message and invalid field using the for attribute (which is always used, no matter the element type). | ||
· Code Sets the error element to "em". $(".selector").validate errorElement: "em" }) | ||
wrapper | String |
|
在出错信息外用其他的元素包装一层。Wrap error labels with the specified element. Useful in combination with errorLabelContainer to create a list of error messages. | ||
· Code Wrap each error element with a list item, useful when using an ordered or unordered list as the error container. $(".selector").validate({ wrapper: "li" }) | ||
errorLabelContainer | Selector |
|
把错误信息统一放在一个容器里面。Hide and show this container when validating. | ||
All error labels are displayed inside an unordered list with the ID "messageBox", as specified by the selector passed as errorContainer option. All error elements are wrapped inside an li element, to create a list of messages. $("#myform").validate({ errorLabelContainer: "#messageBox", wrapper: "li", submitHandler: function() { alert("Submitted!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.mamicode.com/http://code.jquery.com/jquery-latest.js"></script>
<script> $(document).ready(function(){ $("#myform").validate({ errorLabelContainer: "#messageBox", wrapper: "li", submitHandler: function() { alert("Submitted!") } }) }); </script>
</head> <body> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <ul id="messageBox"></ul> <form id="myform" action="/login" method="post"> <label>Firstname</label> <input name="fname" class="required" /> <label>Lastname</label> <input name="lname" title="Your lastname, please!" class="required" /> <br/> <input type="submit" value="http://www.mamicode.com/Submit"/> </form> </body> </html> | ||
errorContainer | Selector |
|
显示或者隐藏验证信息 | ||
使用一个额外的容器去显示错误信息 Uses an additonal container for error messages. The elements given as the errorContainer are all shown and hidden when errors occur. But the error labels themselve are added to the element(s) given as errorLabelContainer, here an unordered list. Therefore the error labels are also wrapped into li elements (wrapper option). $("#myform").validate({ errorContainer: "#messageBox1, #messageBox2", errorLabelContainer: "#messageBox1 ul", wrapper: "li", debug:true, submitHandler: function() { alert("Submitted!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.mamicode.com/http://code.jquery.com/jquery-latest.js"></script>
<script> $(document).ready(function(){ $("#myform").validate({ errorContainer: "#messageBox1, #messageBox2", errorLabelContainer: "#messageBox1 ul", wrapper: "li", debug:true, submitHandler: function() { alert("Submitted!") } }) }); </script> <style>#messageBox1, #messageBox2 { display: none }</style> </head> <body> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <div id="messageBox1"> <ul></ul> </div> <form id="myform" action="/login" method="post"> <label>Firstname</label> <input name="fname" class="required" /> <label>Lastname</label> <input name="lname" title="Your lastname, please!" class="required" /> <br/> <input type="submit" value="http://www.mamicode.com/Submit"/> </form> <div id="messageBox2"> <h3>There are errors in your form, see details above!</h3> </div> </body> </html> | ||
showErrors | Callback | Default: None, uses built-in message disply. |
得到错误的显示句柄 Gets the map of errors as the first argument and and array of errors as the second, called in the context of the validator object. The arguments contain only those elements currently validated, which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default behaviour by calling this.defaultShowErrors(). | ||
· Code Update the number of invalid elements each time an error is displayed. Delegates to the default implementation for the actual error display. $(".selector").validate({ showErrors: function(errorMap, errorList) { $("#summary").html("Your form contains " + this.numberOfInvalids() + " errors, see details below."); this.defaultShowErrors(); } }) | ||
errorPlacement | Callback | Default: 把错误label放在验证的元素后面 |
可选错误label的放置位置. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object. | ||
Use a table layout for the form, placing error messags in the next cell after the input. $("#myform").validate({ errorPlacement: function(error, element) { error.appendTo( element.parent("td").next("td") ); }, debug:true }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.mamicode.com/http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#myform").validate({ errorPlacement: function(error, element) { error.appendTo( element.parent("td").next("td") ); }, debug:true }) }); </script>
</head> <body> <form id="myform" action="/login" method="post"> <table> <tr> <td><label>Firstname</label> <td><input name="fname" class="required" value="http://www.mamicode.com/Pete" /></td> <td></td> </tr> <tr> <td><label>Lastname</label></td> <td><input name="lname" title="Your lastname, please!" class="required" /></td> <td></td> </tr> <tr> <td></td><td><input type="submit" value="http://www.mamicode.com/Submit"/></td><td></td> </table> </form> </body> </html> | ||
success | String , Callback |
|
成功时的class.If specified, the error label is displayed to show a valid element. If a String is given, its added as a class to the label. If a Function is given, its called with the label (as a jQuery object) as its only argument. That can be used to add a text like "ok!". | ||
添加"valid" 到验证验证元素, 在CSS中定义的样式 $("#myform").validate({ success: "valid", submitHandler: function() { alert("Submitted!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.mamicode.com/http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#myform").validate({ success: "valid", submitHandler: function() { alert("Submitted!") } }) }); </script> <style>label.valid { background: url(‘http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif‘) no-repeat; height:16px; width:16px; display: block; position: absolute; top: 4px; left: 152px; }</style> </head> <body>
<form id="myform"> <input type="text" name="email" class="required" /> <br/> <input type="submit" value="http://www.mamicode.com/Submit" /> </form> </body> </html> | ||
添加"valid" 到验证验证元素, 在CSS中定义的样式,并加入“ok”的文字 $("#myform").validate({ success: function(label) { label.addClass("valid").text("Ok!") }, submitHandler: function() { alert("Submitted!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.mamicode.com/http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#myform").validate({ success: function(label) { label.addClass("valid").text("Ok!") }, submitHandler: function() { alert("Submitted!") } }) }); </script> <style>label.valid { background: url(‘http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif‘) no-repeat; height:16px; width:16px; display: block; position: absolute; top: 4px; left: 152px; padding-left: 18px; }</style> </head> <body>
<form id="myform"> <input type="text" name="email" class="required" /> <br/> <input type="submit" value="http://www.mamicode.com/Submit" /> </form> </body> </html> | ||
highlight | Callback | Default: Adds errorClass (see the option) to the Element |
高亮显示错误信息。 或者说重写出错时的出错元素的显示。Override to decide which fields and how to highlight. | ||
· Code Highlights an invalid element by fading it out and in again. $(".selector").validate({ highlight: function(element, errorClass) { $(element).fadeOut(function() { $(element).fadeIn() }) } }) | ||
· Code Adds the error class to both the invalid element and it‘s label $(".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); } }); | ||
unhighlight | Callback | Default: 默认是去掉error类 |
Called to revert changes made by option highlight, same arguments as highlight. |
第三章 自定义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 =http://www.mamicode.com/= param;
};
7: focusInvalid 是否把焦点聚焦在最后一个动作或者最近的一次出错上
$(".selector").validate({
focusInvalid: false
})
8: focusCleanup
如果该属性设置为True, 那么控件获得焦点时,移除出错的class定义,隐藏错误信息,避免和 focusInvalid.一起用。
$(".selector").validate({
focusCleanup: true
})
9: meta
设置meta来封装验证规则
$(".selector").validate({
meta: "validate",
})
第四章 自定义错误消息的显示方式
默认情况下,验证提示信息用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();
}
})
第五章 一些常用的验证脚本
不会写js了,只能从网上找一些常用的验证脚本。
// 手机号码验证
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 =http://www.mamicode.com/="请选择";
}, "必须选择一项");
// 字节长度验证
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个字节)"));
目录
jquery.validate使用攻略1
第一章 jquery.validate使用攻略1
第二章 jQuery.validate.js API7
Custom selectors7
Utilities8
Validator8
List of built-in Validation methods9
validate ()的可选项11
debug:进行调试模式11
第三章 自定义jquery-validate的验证行为23
第四章 自定义错误消息的显示方式25
第五章 一些常用的验证脚本28
转自http://www.cnblogs.com/buzzlight/archive/2010/06/30/1768364.html
jquery.validate使用攻略
第一章 jquery.validate使用攻略
好几年不写JS了,资料整理起来比较慢,格式也有点乱
主要分几部分
jquery.validate 基本用法
jquery.validate API说明
jquery.validate 自定义
jquery.validate 常见类型的验证代码
下载地址
jquery.validate插件的文档地址
http://docs.jquery.com/Plugins/Validation
jquery.validate插件的主页
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
jquery.validate插件主页上提供的demo
http://jquery.bassistance.de/validate/demo/
验证规则
下面是默认校验规则,也可以自定义规则
(1)required:true 必输字段
(2)remote:"check.php" 使用ajax方法调用check.php验证输入值
(3)email:true 必须输入正确格式的电子邮件
(4)url:true 必须输入正确格式的网址
(5)date:true 必须输入正确格式的日期
(6)dateISO:true 必须输入正确格式的日期(ISO),例如:2009-06-23,1998/01/22 只验证格式,不验证有效性
(7)number:true 必须输入合法的数字(负数,小数)
(8)digits:true 必须输入整数
(9)creditcard: 必须输入合法的信用卡号
(10)equalTo:"#field" 输入值必须和#field相同
(11)accept: 输入拥有合法后缀名的字符串(上传文件的后缀)
(12)maxlength:5 输入长度最多是5的字符串(汉字算一个字符)
(13)minlength:10 输入长度最小是10的字符串(汉字算一个字符)
(14)rangelength:[5,10] 输入长度必须介于 5 和 10 之间的字符串")(汉字算一个字符)
(15)range:[5,10] 输入值必须介于 5 和 10 之间
(16)max:5 输入值不能大于5
(17)min:10 输入值不能小于10
验证提示
下面是默认的验证提示,官网有简体中文版的验证提示下载,或者通过jQuery.extend(jQuery.validator.messages自定义错误提示信息,可以将网站的验证提示文本统一到一个文件里。
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}.")
使用方式
1:
在控件中使用默认验证规则,例子:
电子邮件(必填)
<input id="email" class="required email" value="http://www.mamicode.com/email@" />
2:
可以在控件中自定义验证规则,例子:
自定义(必填,[3,5])
<input id="complex" value="http://www.mamicode.com/hi" class="{required:true,minlength:3, maxlength:5,
messages:{required:‘为什么不输入一点文字呢‘,minlength:‘输入的太少了‘,maxlength:‘输入那么多干嘛‘}}" />
3:
通过javascript自定义验证规则,下面的JS自定义了两个规则,password和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除了设置为true/false之外,还可以使用表达式或者函数,比如
$("#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:
使用meta自定义验证信息
首先用JS设置meta
$("#form3").validate({ meta: "validate" });
Html
email<input class="{validate:{required:true, email:true,
messages:{required:‘输入email地址‘, email:‘你输入的不是有效的邮件地址‘}}}"/>
5:
使用meta可以将验证规则写在自定义的标签内,比如validate
JS设置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:
自定义验证规则
对于复杂的验证,可以通过jQuery.validator.addMethod添加自定义的验证规则
官网提供的additional-methods.js里包含一些常用的验证方式,比如lettersonly,ziprange,nowhitespace等
例子
// 字符验证
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:
radio、checkbox、select的验证方式类似
radio的验证
性别
<span>
男<input type="radio" id="gender_male" value="http://www.mamicode.com/m" name="gender" class="{required:true}"/><br />
女<input type="radio" id="gender_female" value="http://www.mamicode.com/f" name="gender" />
</span>
checkbox的验证
最少选择两项
<span>
选项1<input type="checkbox" id="check_1" value="http://www.mamicode.com/1" name="checkGroup"
class="{required:true,minlength:2, messages:{required:‘必须选择‘,minlength:‘至少选择2项‘}}" /><br />
选项2<input type="checkbox" id="check_2" value="http://www.mamicode.com/2" name="checkGroup" /><br />
选项3<input type="checkbox" id="check_3" value="http://www.mamicode.com/3" name="checkGroup" /><br />
</span>
select的验证
下拉框
<span>
<select id="selectbox" name="selectbox" class="{required:true}">
<option value=""></option>
<option value="http://www.mamicode.com/1">1</option>
<option value="http://www.mamicode.com/2">2</option>
<option value="http://www.mamicode.com/3">3</option>
</select>
</span>
8:
Ajax验证
用remote可以进行Ajax验证
remote: {
url: "url", //url地址
type: "post", //发送方式
dataType: "json", //数据格式 data: { //要传递的数据
username: function() {
return $("#username").val();
}}
}
补充: jQuery Validation插件remote验证方式的Bug
http://www.cnblogs.com/JeffreyZhao/archive/2009/12/04/jquery-validate-remote-bug.html
第二章 jQuery.validate.js API
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 |
Custom selectors:
Name | Type |
:blank | Returns: Array <Element > |
没有值的筛选器 | |
:filled | Returns: Array <Element > |
有值的筛选器 | |
:unchecked | Returns: Array <Element > |
没选择的元素的筛选器 |
Utilities
Name | Type |
String utilities:
Name | Type |
jQuery.format( template, argument , argumentN... ) | Returns: String |
用参数代替模板中的 {n}。 |
Validator
validate方法返回一个Validator对象, 它有很多方法, 让你能使用引发校验程序或者改变form的内容. validator对象有很多方法, 但下面只是列出常用的.
Name | Type |
Validator methods:
Name | Type |
form( ) | Returns: Boolean |
验证form返回成功还是失败 | |
element( element ) | Returns: Boolean |
验证单个元素是成功还是失败 | |
resetForm( ) | Returns: undefined |
把前面验证的FORM恢复到验证前原来的状态 | |
showErrors( errors ) | Returns: undefined |
显示特定的错误信息 |
There are a few static methods on the validator object:
Name | Type |
Validator functions:
Name | Type |
setDefaults( defaults ) | Returns: undefined |
改变默认的设置 | |
addMethod( name, method, message ) | Returns: undefined |
添加一个新的验证方法. 必须包括一个独一无二的名字,一个JAVASCRIPT的方法和一个默认的信息 | |
addClassRules( name, rules ) | Returns: undefined |
增加组合验证类型 在一个类里面用多种验证方法里比较有用 | |
addClassRules( rules ) | Returns: undefined |
增加组合验证类型 在一个类里面用多种验证方法里比较有用,这个是一下子加多个 |
[edit ]
List of built-in Validation methods
A set of standard validation methods is provided:
Name | Type |
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 |
验证两个输入框的内容是否相同 |
Name | Type |
phoneUS( ) | Returns: Boolean |
验证美式的电话号码 |
validate ()的可选项
debug:进行调试模式
$(".selector").validate
({
debug: true
})
把调试设置为默认
$.validator.setDefaults({
debug: true
})
submitHandler:用其他方式替代默认的SUBMIT,比如用AJAX的方式提交
$(".selector").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
})
ignore:忽略某些元素不验证
$("#myform").validate({
ignore: ".ignore"
})
rules: 默认下根据form的classes, attributes, metadata判断,但也可以在validate函数里面声明
Key/value 可自定义规则. Key是对象的名字 value是对象的规则,可以组合使用 class/attribute/metadata rules.
以下代码特别验证selector类中name=‘name‘是必填项并且 email是既是必填又要符合email的格式
$(".selector").validate({
rules: {
// simple rule, converted to {required:true}
name: "required",
// compound rule
email: {
required: true,
email: true
}
}
})
messages:更改默认的提示信息
$(".selector").validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please specify your name",
email: {
required: "We need your email address to contact you",
email: "Your email address must be in the format of name@domain.com"
}
}
})
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
})
nsubmit | Boolean | Default: true |
提交时验证. 设置唯false就用其他方法去验证 | ||
· Code 不用onsubmit验证,就允许用户无论用什么方法去验证,而是提交时, 用 keyup/blur/click 等方法. $(".selector").validate({ onsubmit: false }) | ||
onfocusout | Boolean | Default: true |
Validate elements (except checkboxes/radio buttons) on blur. If nothing is entered, all rules are skipped, except when the field was already marked as invalid. | ||
· Code Disables onblur validation. $(".selector").validate({ onfocusout: false }) | ||
onkeyup | Boolean | Default: true |
在keyup时验证. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. | ||
· Code Disables onkeyup validation. $(".selector").validate({ onkeyup: false }) | ||
onclick | Boolean | Default: true |
在checkboxes 和 radio 点击时验证. | ||
· Code Disables onclick validation of checkboxes and radio buttons. $(".selector").validate({ onclick: false }) | ||
focusInvalid | Boolean | Default: true |
把焦点聚焦在最后一个动作或者最近的一次出错上via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding to steal its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off. | ||
· Code Disables focusing of invalid elements. $(".selector").validate({ focusInvalid: false }) | ||
focusCleanup | Boolean | Default: false |
如果是true那么删除出错类从出错的元素上并且隐藏出错信息当这个元素被聚焦 .避免和 focusInvalid.一起用 | ||
· Code Enables cleanup when focusing elements, removing the error class and hiding error messages when an element is focused. $(".selector").validate({ focusCleanup: true }) | ||
meta | String |
|
为了元数据使用其他插件你要包装 你的验证规则 在他们自己的项目中可以用这个特殊的选项 | ||
Tell the validation plugin to look inside a validate-property in metadata for validation rules. $("#myform").validate({ meta: "validate", submitHandler: function() { alert("Submitted!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.mamicode.com/http://code.jquery.com/jquery-latest.js"></script>
<script> $(document).ready(function(){ $("#myform").validate({ meta: "validate", submitHandler: function() { alert("Submitted!") } }) }); </script>
</head> <body> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.metadata.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <form id="myform"> <input type="text" name="email" class="{validate:{ required: true, email:true }}" /> <br/> <input type="submit" value="http://www.mamicode.com/Submit" /> </form> </body> </html> | ||
errorClass | String | Default: "error" |
创建错误类的名字为了去寻找存在的错误标签和增加它到验证失败的元素中去。 | ||
· Code Sets the error class to "invalid". $(".selector").validate({ errorClass: "invalid" }) | ||
errorElement | String | Default: "label" |
设置错误的元素,默认的是label你可以改成em.Use this element type to create error messages and to look for existing error messages. The default, "label", has the advantage of creating a meaningful link between error message and invalid field using the for attribute (which is always used, no matter the element type). | ||
· Code Sets the error element to "em". $(".selector").validate errorElement: "em" }) | ||
wrapper | String |
|
在出错信息外用其他的元素包装一层。Wrap error labels with the specified element. Useful in combination with errorLabelContainer to create a list of error messages. | ||
· Code Wrap each error element with a list item, useful when using an ordered or unordered list as the error container. $(".selector").validate({ wrapper: "li" }) | ||
errorLabelContainer | Selector |
|
把错误信息统一放在一个容器里面。Hide and show this container when validating. | ||
All error labels are displayed inside an unordered list with the ID "messageBox", as specified by the selector passed as errorContainer option. All error elements are wrapped inside an li element, to create a list of messages. $("#myform").validate({ errorLabelContainer: "#messageBox", wrapper: "li", submitHandler: function() { alert("Submitted!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.mamicode.com/http://code.jquery.com/jquery-latest.js"></script>
<script> $(document).ready(function(){ $("#myform").validate({ errorLabelContainer: "#messageBox", wrapper: "li", submitHandler: function() { alert("Submitted!") } }) }); </script>
</head> <body> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <ul id="messageBox"></ul> <form id="myform" action="/login" method="post"> <label>Firstname</label> <input name="fname" class="required" /> <label>Lastname</label> <input name="lname" title="Your lastname, please!" class="required" /> <br/> <input type="submit" value="http://www.mamicode.com/Submit"/> </form> </body> </html> | ||
errorContainer | Selector |
|
显示或者隐藏验证信息 | ||
使用一个额外的容器去显示错误信息 Uses an additonal container for error messages. The elements given as the errorContainer are all shown and hidden when errors occur. But the error labels themselve are added to the element(s) given as errorLabelContainer, here an unordered list. Therefore the error labels are also wrapped into li elements (wrapper option). $("#myform").validate({ errorContainer: "#messageBox1, #messageBox2", errorLabelContainer: "#messageBox1 ul", wrapper: "li", debug:true, submitHandler: function() { alert("Submitted!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.mamicode.com/http://code.jquery.com/jquery-latest.js"></script>
<script> $(document).ready(function(){ $("#myform").validate({ errorContainer: "#messageBox1, #messageBox2", errorLabelContainer: "#messageBox1 ul", wrapper: "li", debug:true, submitHandler: function() { alert("Submitted!") } }) }); </script> <style>#messageBox1, #messageBox2 { display: none }</style> </head> <body> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <div id="messageBox1"> <ul></ul> </div> <form id="myform" action="/login" method="post"> <label>Firstname</label> <input name="fname" class="required" /> <label>Lastname</label> <input name="lname" title="Your lastname, please!" class="required" /> <br/> <input type="submit" value="http://www.mamicode.com/Submit"/> </form> <div id="messageBox2"> <h3>There are errors in your form, see details above!</h3> </div> </body> </html> | ||
showErrors | Callback | Default: None, uses built-in message disply. |
得到错误的显示句柄 Gets the map of errors as the first argument and and array of errors as the second, called in the context of the validator object. The arguments contain only those elements currently validated, which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default behaviour by calling this.defaultShowErrors(). | ||
· Code Update the number of invalid elements each time an error is displayed. Delegates to the default implementation for the actual error display. $(".selector").validate({ showErrors: function(errorMap, errorList) { $("#summary").html("Your form contains " + this.numberOfInvalids() + " errors, see details below."); this.defaultShowErrors(); } }) | ||
errorPlacement | Callback | Default: 把错误label放在验证的元素后面 |
可选错误label的放置位置. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object. | ||
Use a table layout for the form, placing error messags in the next cell after the input. $("#myform").validate({ errorPlacement: function(error, element) { error.appendTo( element.parent("td").next("td") ); }, debug:true }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.mamicode.com/http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#myform").validate({ errorPlacement: function(error, element) { error.appendTo( element.parent("td").next("td") ); }, debug:true }) }); </script>
</head> <body> <form id="myform" action="/login" method="post"> <table> <tr> <td><label>Firstname</label> <td><input name="fname" class="required" value="http://www.mamicode.com/Pete" /></td> <td></td> </tr> <tr> <td><label>Lastname</label></td> <td><input name="lname" title="Your lastname, please!" class="required" /></td> <td></td> </tr> <tr> <td></td><td><input type="submit" value="http://www.mamicode.com/Submit"/></td><td></td> </table> </form> </body> </html> | ||
success | String , Callback |
|
成功时的class.If specified, the error label is displayed to show a valid element. If a String is given, its added as a class to the label. If a Function is given, its called with the label (as a jQuery object) as its only argument. That can be used to add a text like "ok!". | ||
添加"valid" 到验证验证元素, 在CSS中定义的样式 $("#myform").validate({ success: "valid", submitHandler: function() { alert("Submitted!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.mamicode.com/http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#myform").validate({ success: "valid", submitHandler: function() { alert("Submitted!") } }) }); </script> <style>label.valid { background: url(‘http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif‘) no-repeat; height:16px; width:16px; display: block; position: absolute; top: 4px; left: 152px; }</style> </head> <body>
<form id="myform"> <input type="text" name="email" class="required" /> <br/> <input type="submit" value="http://www.mamicode.com/Submit" /> </form> </body> </html> | ||
添加"valid" 到验证验证元素, 在CSS中定义的样式,并加入“ok”的文字 $("#myform").validate({ success: function(label) { label.addClass("valid").text("Ok!") }, submitHandler: function() { alert("Submitted!") } }) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="http://www.mamicode.com/http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#myform").validate({ success: function(label) { label.addClass("valid").text("Ok!") }, submitHandler: function() { alert("Submitted!") } }) }); </script> <style>label.valid { background: url(‘http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif‘) no-repeat; height:16px; width:16px; display: block; position: absolute; top: 4px; left: 152px; padding-left: 18px; }</style> </head> <body>
<form id="myform"> <input type="text" name="email" class="required" /> <br/> <input type="submit" value="http://www.mamicode.com/Submit" /> </form> </body> </html> | ||
highlight | Callback | Default: Adds errorClass (see the option) to the Element |
高亮显示错误信息。 或者说重写出错时的出错元素的显示。Override to decide which fields and how to highlight. | ||
· Code Highlights an invalid element by fading it out and in again. $(".selector").validate({ highlight: function(element, errorClass) { $(element).fadeOut(function() { $(element).fadeIn() }) } }) | ||
· Code Adds the error class to both the invalid element and it‘s label $(".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); } }); | ||
unhighlight | Callback | Default: 默认是去掉error类 |
Called to revert changes made by option highlight, same arguments as highlight. |
第三章 自定义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 =http://www.mamicode.com/= param;
};
7: focusInvalid 是否把焦点聚焦在最后一个动作或者最近的一次出错上
$(".selector").validate({
focusInvalid: false
})
8: focusCleanup
如果该属性设置为True, 那么控件获得焦点时,移除出错的class定义,隐藏错误信息,避免和 focusInvalid.一起用。
$(".selector").validate({
focusCleanup: true
})
9: meta
设置meta来封装验证规则
$(".selector").validate({
meta: "validate",
})
第四章 自定义错误消息的显示方式
默认情况下,验证提示信息用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();
}
})
第五章 一些常用的验证脚本
不会写js了,只能从网上找一些常用的验证脚本。
// 手机号码验证
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 =http://www.mamicode.com/="请选择";
}, "必须选择一项");
// 字节长度验证
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个字节)"));
jquery.validate使用攻略(表单校验)