jQuery Validate 插件為表單提供了強大的驗證功能,讓客戶端表單驗證變得更簡單,同時提供了大量的定制選項,滿足應(yīng)用程序各種需求。該插件捆綁了一套有用的驗證方法,包括 URL 和電子郵件驗證,同時提供了一個用來編寫用戶自定義方法的 API。所有的捆綁方法默認(rèn)使用英語作為錯誤信息,且已翻譯成其他 37 種語言。
該插件是由 Jörn Zaefferer 編寫和維護(hù)的,他是 jQuery 團隊的一名成員,是 jQuery UI 團隊的主要開發(fā)人員,是 QUnit 的維護(hù)人員。該插件在 2006 年 jQuery 早期的時候就已經(jīng)開始出現(xiàn),并一直更新至今。目前版本是 1.14.0。
訪問 jQuery Validate 官網(wǎng),下載最新版的 jQuery Validate 插件。
動力節(jié)點提供的 1.14.0 版本下載地址:http://static.runoob.com/download/jquery-validation-1.14.0.zip
導(dǎo)入 js 庫(使用動力節(jié)點提供的CDN)
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
默認(rèn)校驗規(guī)則
序號 |
規(guī)則 |
描述 |
---|---|---|
1 |
required:true |
必須輸入的字段。 |
2 |
remote:"check.php" |
使用 ajax 方法調(diào)用 check.php 驗證輸入值。 |
3 |
email:true |
必須輸入正確格式的電子郵件。 |
4 |
url:true |
必須輸入正確格式的網(wǎng)址。 |
5 |
date:true |
必須輸入正確格式的日期。日期校驗 ie6 出錯,慎用。 |
6 |
dateISO:true |
必須輸入正確格式的日期(ISO),例如:2009-06-23,1998/01/22。只驗證格式,不驗證有效性。 |
7 |
number:true |
必須輸入合法的數(shù)字(負(fù)數(shù),小數(shù))。 |
8 |
digits:true |
必須輸入整數(shù)。 |
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。 |
默認(rèn)提示
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.",
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}." )
}
jQuery Validate提供了中文信息提示包,位于下載包的 dist/localization/messages_zh.js,內(nèi)容如下:
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
define( ["jquery", "../jquery.validate"], factory );
} else {
factory( jQuery );
}
}(function( $ ) {
/*
* Translated default messages for the jQuery validation plugin.
* Locale: ZH (Chinese, 中文 (Zhōngwén), 漢語, 漢語)
*/
$.extend($.validator.messages, {
required: "這是必填字段",
remote: "請修正此字段",
email: "請輸入有效的電子郵件地址",
url: "請輸入有效的網(wǎng)址",
date: "請輸入有效的日期",
dateISO: "請輸入有效的日期 (YYYY-MM-DD)",
number: "請輸入有效的數(shù)字",
digits: "只能輸入數(shù)字",
creditcard: "請輸入有效的信用卡號碼",
equalTo: "你的輸入不相同",
extension: "請輸入有效的后綴",
maxlength: $.validator.format("最多可以輸入 {0} 個字符"),
minlength: $.validator.format("最少要輸入 {0} 個字符"),
rangelength: $.validator.format("請輸入長度在 {0} 到 {1} 之間的字符串"),
range: $.validator.format("請輸入范圍在 {0} 到 {1} 之間的數(shù)值"),
max: $.validator.format("請輸入不大于 {0} 的數(shù)值"),
min: $.validator.format("請輸入不小于 {0} 的數(shù)值")
});
}));
你可以將該本地化信息文件 dist/localization/messages_zh.js 引入到頁面:
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
使用方式
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
<script>
$.validator.setDefaults({
submitHandler: function() {
alert("提交事件!");
}
});
$().ready(function() {
$("#commentForm").validate();
});
</script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>輸入您的名字,郵箱,URL,備注。</legend>
<p>
<label for="cname">Name (必需, 最小兩個字母)</label>
<input id="cname" name="name" minlength="2" type="text" required>
</p>
<p>
<label for="cemail">E-Mail (必需)</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
<label for="curl">URL (可選)</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">備注 (必需)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
2、將校驗規(guī)則寫到 js 代碼中
$().ready(function() {
// 在鍵盤按下并釋放及提交后驗證提交表單
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "請輸入您的名字",
lastname: "請輸入您的姓氏",
username: {
required: "請輸入用戶名",
minlength: "用戶名必需由兩個字符組成"
},
password: {
required: "請輸入密碼",
minlength: "密碼長度不能小于 5 個字符"
},
confirm_password: {
required: "請輸入密碼",
minlength: "密碼長度不能小于 5 個字符",
equalTo: "兩次密碼輸入不一致"
},
email: "請輸入一個正確的郵箱",
agree: "請接受我們的聲明",
topic: "請選擇兩個主題"
}
})
});
messages 處,如果某個控件沒有 message,將調(diào)用默認(rèn)的信息
<form class="cmxform" id="signupForm" method="get" action="">
<fieldset>
<legend>驗證完整的表單</legend>
<p>
<label for="firstname">名字</label>
<input id="firstname" name="firstname" type="text">
</p>
<p>
<label for="lastname">姓氏</label>
<input id="lastname" name="lastname" type="text">
</p>
<p>
<label for="username">用戶名</label>
<input id="username" name="username" type="text">
</p>
<p>
<label for="password">密碼</label>
<input id="password" name="password" type="password">
</p>
<p>
<label for="confirm_password">驗證密碼</label>
<input id="confirm_password" name="confirm_password" type="password">
</p>
<p>
<label for="email">Email</label>
<input id="email" name="email" type="email">
</p>
<p>
<label for="agree">請同意我們的聲明</label>
<input type="checkbox" class="checkbox" id="agree" name="agree">
</p>
<p>
<label for="newsletter">我樂意接收新信息</label>
<input type="checkbox" class="checkbox" id="newsletter" name="newsletter">
</p>
<fieldset id="newsletter_topics">
<legend>主題 (至少選擇兩個) - 注意:如果沒有勾選“我樂意接收新信息”以下選項會隱藏,但我們這里作為演示讓它可見</legend>
<label for="topic_marketflash">
<input type="checkbox" id="topic_marketflash" value="marketflash" name="topic">Marketflash
</label>
<label for="topic_fuzz">
<input type="checkbox" id="topic_fuzz" value="fuzz" name="topic">Latest fuzz
</label>
<label for="topic_digester">
<input type="checkbox" id="topic_digester" value="digester" name="topic">Mailing list digester
</label>
<label for="topic" class="error">Please select at least two topics you'd like to receive.</label>
</fieldset>
<p>
<input class="submit" type="submit" value="提交">
</p>
</fieldset>
</form>
required: true 值是必須的。
required: "#aa:checked" 表達(dá)式的值為真,則需要驗證。
required: function(){} 返回為真,表示需要驗證。
后邊兩種常用于,表單中需要同時填或不填的元素。
常用方法及注意問題
$().ready(function() {
$("#signupForm").validate({
submitHandler:function(form){
alert("提交事件!");
form.submit();
}
});
});
使用 ajax 方式
$(".selector").validate({
submitHandler: function(form)
{
$(form).ajaxSubmit();
}
})
可以設(shè)置 validate 的默認(rèn)值,寫法如下:
$.validator.setDefaults({
submitHandler: function(form) { alert("提交事件!");form.submit(); }
});
如果想提交表單, 需要使用 form.submit(),而不要使用 $(form).submit()。
如果這個參數(shù)為true,那么表單不會提交,只進(jìn)行檢查,調(diào)試時十分方便。
$().ready(function() {
$("#signupForm").validate({
debug:true
});
});
如果一個頁面中有多個表單都想設(shè)置成為 debug,則使用:
$.validator.setDefaults({
debug: true
})
3、ignore:忽略某些元素不驗證
ignore: ".ignore"
4、更改錯誤信息顯示的位置
errorPlacement:Callback
指明錯誤放置的位置,默認(rèn)情況是:error.appendTo(element.parent());即把錯誤信息放在驗證的元素后面。
errorPlacement: function(error, element) {
error.appendTo(element.parent());
}
實例
<p>將錯誤信息放在 label 元素后并使用 span 元素包裹它</p>
<form method="get" class="cmxform" id="form1" action="">
<fieldset>
<legend>Login Form</legend>
<p>
<label for="user">Username</label>
<input id="user" name="user" required minlength="3">
</p>
<p>
<label for="password">Password</label>
<input id="password" type="password" maxlength="12" name="password" required minlength="5">
</p>
<p>
<input class="submit" type="submit" value="Login">
</p>
</fieldset>
</form>
代碼的作用是:一般情況下把錯誤信息顯示在 <td class="status"></td>中,如果是 radio 則顯示在 <td></td>中,如果是 checkbox 則顯示在內(nèi)容的后面。
參數(shù) |
類型 |
描述 |
默認(rèn)值 |
---|---|---|---|
errorClass |
String |
指定錯誤提示的 css 類名,可以自定義錯誤提示的樣式。 |
"error" |
errorElement |
String |
用什么標(biāo)簽標(biāo)記錯誤,默認(rèn)是 label,可以改成 em。 |
"label" |
errorContainer |
Selector |
顯示或者隱藏驗證信息,可以自動實現(xiàn)有錯誤信息出現(xiàn)時把容器屬性變?yōu)轱@示,無錯誤時隱藏,用處不大。 errorContainer: "#messageBox1, #messageBox2" |
|
errorLabelContaine |
Selector |
把錯誤信息統(tǒng)一放在一個容器里面。 |
|
wrapper |
String |
用什么標(biāo)簽再把上邊的 errorELement 包起來。 |
一般這三個屬性同時使用,實現(xiàn)在一個容器內(nèi)顯示所有錯誤提示的功能,并且沒有信息時自動隱藏。
errorContainer: "div.error",
errorLabelContainer: $("#signupForm div.error"),
wrapper: "li"
5、更改錯誤信息顯示的樣式
設(shè)置錯誤提示的樣式,可以增加圖標(biāo)顯示,在該系統(tǒng)中已經(jīng)建立了一個 validation.css,專門用于維護(hù)校驗文件的樣式。
input.error { border: 1px solid red; }
label.error {
background:url("./demo/images/unchecked.gif") no-repeat 0px 0px;
padding-left: 16px;
padding-bottom: 2px;
font-weight: bold;
color: #EA5200;
}
label.checked {
background:url("./demo/images/checked.gif") no-repeat 0px 0px;
}
6、每個字段驗證通過執(zhí)行函數(shù)
success:String,Callback
要驗證的元素通過驗證后的動作,如果跟一個字符串,會當(dāng)作一個 css 類,也可跟一個函數(shù)。
success: function(label) {
// set as text for IE
label.html(" ").addClass("checked");
//label.addClass("valid").text("Ok!")
}
添加 "valid" 到驗證元素,在 CSS 中定義的樣式 <style>label.valid {}</style>。
success: "valid"
7、驗證的觸發(fā)方式修改
下面的雖然是 boolean 型的,但建議除非要改為 false,否則別亂添加。
觸發(fā)方式 |
類型 |
描述 |
默認(rèn)值 |
---|---|---|---|
onsubmit |
Boolean |
交時驗證。設(shè)置為 false 就用其他方法去驗證。 |
true |
onfocusout |
Boolean |
失去焦點時驗證(不包括復(fù)選框/單選按鈕)。 |
true |
onkeyup |
Boolean |
在 keyup 時驗證。 |
true |
onclick |
Boolean |
在點擊復(fù)選框和單選按鈕時驗證。 |
true |
focusInvalid |
Boolean |
提交表單后,未通過驗證的表單(第一個或提交之前獲得焦點的未通過驗證的表單)會獲得焦點。 |
true |
focusCleanup |
Boolean |
如果是 true 那么當(dāng)未通過驗證的元素獲得焦點時,移除錯誤提示。避免和 focusInvalid 一起用。 |
false |
// 重置表單
$().ready(function() {
var validator = $("#signupForm").validate({
submitHandler:function(form){
alert("submitted");
form.submit();
}
});
$("#reset").click(function() {
validator.resetForm();
});
});
8、異步驗證
remote:URL
使用 ajax 方式進(jìn)行驗證,默認(rèn)會提交當(dāng)前驗證的值到遠(yuǎn)程地址,如果需要提交其他的值,可以使用 data 選項。
remote: "check-email.php"
remote: {
url: "check-email.php", //后臺處理程序
type: "post", //數(shù)據(jù)發(fā)送方式
dataType: "json", //接受數(shù)據(jù)格式
data: { //要傳遞的數(shù)據(jù)
username: function() {
return $("#username").val();
}
}
}
遠(yuǎn)程地址只能輸出 "true" 或 "false",不能有其他輸出。
addMethod:name, method, message
自定義驗證方法
// 中文字兩個字節(jié)
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}個字節(jié)之間(一個中文字算2個字節(jié))"));
// 郵政編碼驗證
jQuery.validator.addMethod("isZipCode", function(value, element) {
var tel = /^[0-9]{6}$/;
return this.optional(element) || (tel.test(value));
}, "請正確填寫您的郵政編碼");
注意:要在 additional-methods.js 文件中添加或者在 jquery.validate.js 文件中添加。建議一般寫在 additional-methods.js 文件中。
注意:在 messages_cn.js 文件中添加:isZipCode: "只能包括中文字、英文字母、數(shù)字和下劃線"。調(diào)用前要添加對 additional-methods.js 文件的引用。
radio 的 required 表示必須選中一個。
<input type="radio" id="gender_male" value="m" name="gender" required />
<input type="radio" id="gender_female" value="f" name="gender"/>
checkbox 的 required 表示必須選中。
<input type="checkbox" class="checkbox" id="agree" name="agree" required />
checkbox 的 minlength 表示必須選中的最小個數(shù),maxlength 表示最大的選中個數(shù),rangelength:[2,3] 表示選中個數(shù)區(qū)間。
<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" required minlength="2" />
<input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" />
<input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" />
select 的 required 表示選中的 value 不能為空。
<select id="jungle" name="jungle" title="Please select something!" required>
<option value=""></option>
<option value="1">Buga</option>
<option value="2">Baga</option>
<option value="3">Oi</option>
</select>
select 的 minlength 表示選中的最小個數(shù)(可多選的 select),maxlength 表示最大的選中個數(shù),rangelength:[2,3] 表示選中個數(shù)區(qū)間。
<select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, minlength:2}" multiple="multiple">
<option value="b">Banana</option>
<option value="a">Apple</option>
<option value="p">Peach</option>
<option value="t">Turtle</option>
</select>