jQuery-使用Validation來驗證表單

268520_2170889401574_3250508_n

在製作網站的時候常常會有機會用到驗證使用者輸入資料的時候,比方說請他輸入數字,你要知道他是不是有輸入非數字的字員,請他輸入email,他有沒有照email的格式來輸入,資料輸入錯誤,都會造成取得資料上的困擾,於是就必須要靠javascript來做一些資料驗證的動作,讓資料送出去時,確保起碼的正確性,但其實要做資料的驗證也是頗麻煩的一件事,加上如果發現他資料輸入錯誤,又要出現提示錯誤的訊息,每次都要重做一次就會顯得很麻煩,但我們可以使用jQuery的外掛Validation來簡單的做到驗證資料的功能。

當然首先請到官網去下載外掛,並在網頁中引入外掛的js檔。

然後建立你的表單。
<form class="cmxform" id="signupForm" method="get" action="">
<fieldset>
<legend>Validating a complete form</legend>

<label for="firstname">Firstname</label>
<input id="firstname" name="firstname" />

<label for="lastname">Lastname</label>
<input id="lastname" name="lastname" />

<label for="username">Username</label>
<input id="username" name="username" />

<label for="password">Password</label>
<input id="password" name="password" type="password" />

<label for="confirm_password">Confirm password</label>
<input id="confirm_password" name="confirm_password" type="password" />

<label for="email">Email</label>
<input id="email" name="email" />

</fieldset>
</form>

接下來將表單的元素指定給validation:
$("#signupForm").validate({
});

然後你可以使用rules去定義每一個input應該輸入的值

可以使用以下這些參數:
(1) required: true 必輸
(2) number: true 只能輸入數字(包括小數)
(3) digits:true 只能輸入整數
(4) minValue: 3 不能小於3
(5) maxValue: 100 最大不超過100
(6) rangeValue:[50,100] 值範圍為50-100
(7) minLength: 5 最小長度(漢字算一個字符)
(8) maxLength: 10 最大長度(漢字算一個字符)
(9) rangeLength:[5,10] 長度範圍為5至10位(漢字算一個字符)
(10) 上面的minLength, maxLength, rangeLength 這三項除了text input之外還可以用於checkbox,select這兩種控件
(11) email:true 電子郵件
(12) equalTo: "#field" 與#field值相同
(13) dateISO:true 日期型,格式為1998/01/22 1999-12-12

另外如果輸入的不符合規則,則可在message定義出現錯誤後顯示的文字:
messages {
password: {
required: "請輸入您的密碼."
minLength: "密碼不能小於5位.",
maxLength: "密碼不能長於32位."
},

觀看效果

參考資料:
Plugins/Validation
jQuery Validate 詳細使用說明

留言