在作網頁表單時時常須要在客戶端對錶單填寫的數據進行驗證一番才能提交,咱們能夠經過本身編寫JavasScript代碼來驗證,可是有時數據量過多時就會有些難度了。基於jQuery的jquery.validate驗證框架幫咱們解決了困難,咱們能夠經過它迅速驗證一些常見的輸入,而且能夠本身擴充本身的驗證方法,並且對國際化也有很是好的支持。 javascript
今天記錄的就是用此插件來實現表單驗證,效果圖: html
一、獲取JS文件:http://jqueryvalidation.org/,這個插件的用法就再也不多講了,如不熟悉或者還沒用過的能夠經過官網瞭解也能夠搜索jquery validate中文API,此文僅僅記錄如何實現上圖效果。 java
二、導入JS jquery
<script src="test/jquery.js" type="text/javascript"></script>
<script src="test/jquery.validate.js" type="text/javascript"></script>
三、建立表單 git
<fieldset style="width:700px; margin:0 auto;">
<legend>用戶註冊</legend>
<form id="signupForm" method="get" action="">
<p>
<label
for="firstname">用戶名:</label>
<input id="firstname" name="firstname" type="text" />
<span class="red">*</span>
</p>
<p>
<label
for="realname">真實名:</label>
<input id="realname" name="realname" type="text" />
</p>
<p>
<label
for="password">密 碼:</label>
<input id="password" name="password" type="password" />
<span class="red">*</span>
</p>
<p>
<label
for="confirm_password">確 認:</label>
<input id="confirm_password" name="confirm_password" type="password" />
<span class="red">*</span>
</p>
<p>
<label
for="email">郵 箱:</label>
<input id="email" name="email" type="text" />
<span class="red">*</span>
</p>
<p>
<label
for="tel">電 話:</label>
<input id="tel" name="tel" type="text" />
</p>
<p>
<label
for="address">地 址:</label>
<input id="address" name="address" type="text" />
</p>
<p>
<label
for="idcard">證件號:</label>
<input id="idcard" name="idcard" type="text" />
</p>
<p>
<label
for="degree">學 歷:</label>
<select id="degree" name="degree">
<option value="-1">請選擇</option>
<option value="1">小學</option>
<option value="2">中學</option>
<option value="3">大專</option>
<option value="4">本科</option>
<option value="5">學士</option>
<option value="6">碩士</option>
<option value="7">博士</option>
</select>
</p>
<p>
<label
for="sex">性 別:</label>
<input type="radio" id="rdoFemale" name="sex" />男
<input type="radio" id="rdoMale" name="sex" />女
<input type="radio" id="rdoSecret" name="sex" />保密
</p>
<p>
<input id="read" name="read" type="checkbox" /><label for="read">贊成相關條約</label>
</p>
<p>
<input class="submit" type="submit" value="Register"/>
</p>
</form>
</fieldset>
四、表單初始化樣式 網絡
.red{
color:
red;}
.submit{
width:
80px;}
input{
height:
22px;
padding:
2px;}
五、驗證代碼 app
$(document).ready(
function() {
//
設置默認屬性
$.validator.setDefaults({
submitHandler:
function(form) {
form.submit();
}
}),
//
開始驗證
$("#signupForm").validate({
rules: {
firstname: {
required:
true,
stringCheck:
true,
byteRangeLength:[4,15]
},
realname: {
minlength:5
},
password: {
required:
true,
minlength: 5
},
confirm_password: {
required:
true,
minlength: 5,
equalTo: "#password"
},
email: {
required:
true,
email:
true
},
tel: {
isMobile:
true
},
address: {
stringCheck:
true,
byteRangeLength:[4,100]
},
read: {
required:
true
},
degree: {
required:
true,
min:0
},
idcard: {
required:
true,
isIdCardNo:
true
}
},
//
設置提示信息
messages:{
address:{
stringCheck: "請正確輸入您的聯繫地址",
byteRangeLength: "請詳實您的聯繫地址以便於咱們聯繫您"
},
read:{
required:"請先閱讀註冊條約"
},
degree:{
min:"請選擇學歷"
}
},
//
設置錯誤信息存放標籤
errorElement: "em",
//
指定錯誤信息位置
errorPlacement:
function (error, element) {
if (element.is(':radio') || element.is(':checkbox')) {
var eid = element.attr('name');
error.appendTo(element.parent());
}
else {
error.appendTo(element.closest("p"));
}
},
//
設置驗證觸發事件
focusInvalid:
true,
//
設置驗證成功提示格式
success:
function(e)
{
e.html(" ").addClass("valid").text('ok');
}
})
});
到這裏表單驗證功能就初步完成了,能夠試着預覽一下效果,點擊按鈕提交你確定發現不會進行驗證,由於在驗證中使用了一些自定義的方法,因此驗證失效,那麼繼續讀下去吧,接下來是實現驗證的提示信息的個性化和自定義驗證方法。 框架
六、咱們能夠知道validate默認的提示信息是英文的,咱們能夠編寫一個jquery.validate.message_cn.js文件來改變它的提示內容並讓提示內容顯示成中文的: ui
//
定義中文消息
var cnmsg = {
required: "必需填寫項",
remote: "請修正該字段",
email: "請輸入正確格式的電子郵件",
url: "請輸入合法的網址",
date: "請輸入合法的日期",
dateISO: "請輸入合法的日期 (ISO).",
number: "請輸入合法的數字",
digits: "只能輸入整數",
creditcard: "請輸入合法的信用卡號",
equalTo: "請再次輸入相同的值",
accept: "請輸入擁有合法後綴名的字符串",
maxlength: jQuery.format("請輸入一個長度最可能是 {0} 的字符串"),
minlength: jQuery.format("請輸入一個長度最少是 {0} 的字符串"),
rangelength: jQuery.format("請輸入一個長度介於 {0} 和 {1} 之間的字符串"),
range: jQuery.format("請輸入一個介於 {0} 和 {1} 之間的值"),
max: jQuery.format("請輸入一個最大爲 {0} 的值"),
min: jQuery.format("請輸入一個最小爲 {0} 的值"),
//
自定義驗證方法的提示信息
stringCheck: "用戶名只能包括中文字、英文字母、數字和下劃線",
byteRangeLength: "用戶名必須在4-15個字符之間(一箇中文字算2個字符)",
isIdCardNo: "請正確輸入您的身份證號碼",
};
jQuery.extend(jQuery.validator.messages, cnmsg);
能夠看到此文件中有一個自定義驗證方法的提示信息,這些驗證方法也是讓以前預覽沒有驗證效果的原兇哦,validate插件提供自定義驗證方法,繼續完善 jquery.validate.message_cn.js(自定義驗證方法來源於網絡) 文件: this
//
字符驗證
jQuery.validator.addMethod("stringCheck",
function(value, element) {
return
this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value);
}, "只能包括中文字、英文字母、數字和下劃線");
//
中文字兩個字節
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] );
}, "請確保輸入的值在4-15個字節之間(一箇中文字算2個字節)");
//
身份證號碼驗證
jQuery.validator.addMethod("isIdCardNo",
function(value, element) {
return
this.optional(element) || isIdCardNo(value);
}, "請正確輸入您的身份證號碼");
/*
*
* 身份證號碼驗證
*/
function isIdCardNo(num) {
var factorArr =
new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1);
var parityBit=
new Array("1","0","X","9","8","7","6","5","4","3","2");
var varArray =
new Array();
var intValue;
var lngProduct = 0;
var intCheckDigit;
var intStrLen = num.length;
var idNumber = num;
//
initialize
if ((intStrLen != 15) && (intStrLen != 18)) {
return
false;
}
//
check and set value
for(i=0;i<intStrLen;i++) {
varArray[i] = idNumber.charAt(i);
if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) {
return
false;
}
else
if (i < 17) {
varArray[i] = varArray[i] * factorArr[i];
}
}
if (intStrLen == 18) {
//
check date
var date8 = idNumber.substring(6,14);
if (isDate8(date8) ==
false) {
return
false;
}
//
calculate the sum of the products
for(i=0;i<17;i++) {
lngProduct = lngProduct + varArray[i];
}
//
calculate the check digit
intCheckDigit = parityBit[lngProduct % 11];
//
check last digit
if (varArray[17] != intCheckDigit) {
return
false;
}
}
else{
//
length is 15
//
check date
var date6 = idNumber.substring(6,12);
if (isDate6(date6) ==
false) {
return
false;
}
}
return
true;
}
在文件中導入jquery.validate.message_cn.js文件
<script src="test/jquery.validate.message_cn.js" type="text/javascript"></script>