fValidator和iMask都是來自http://zend.lojcomm.com.br的JS腳本。http://zend.lojcomm.com.br還提供了實現內容滾動特效和圖片的魚眼特效的js腳本。但是在這裏,只討論如何通過fValidator和iMask來快速構建客戶端驗證。
首先,還是先看http://zend.lojcomm.com.br提供的例子:http://zend.lojcomm.com.br/fvalidator/exampleB.asp
怎麼樣?是不是很酷?
實際上,關於如何使用fValidator和iMask,官方網站已經提供了簡單明瞭的說明。fValidator和iMask依賴於另一個js——mootools.js。
官方說可以從http://mootools.net/下載mootools.js,但是現在的mootools.js的版本是1.1.1,與fValidator搭配似乎有問題。官方提供的例子中使用的是mootools.v1.1.js,可以從這裏下載:http://zend.lojcomm.com.br/common/js/mootools.v1.1.js,
iMask.js從這裏下載:http://zend.lojcomm.com.br/imask/js/iMask-full.js,
fValidator.js從這裏下載:http://zend.lojcomm.com.br/fvalidator/js/fValidator-full.js
分別下載上述三個js之後,就可以開始構建我們的JS應用了。按照官方的Simple,可以很快地看到結果。fValiator和iMask分別通過表單元素的class屬性和alt屬性註冊並設定相關參數。
如:
<input id="exB_Email" class="fValidate['required','email']" name="email" type="text" />
這樣,我們只需要添加這樣一行JS代碼,就可以擁有默認的表單驗證:
window.addEvent("domready", function() { var exValidatorB = new fValidator("exB"); });
這段代碼會遍歷id=exb的Form中的所欲元素,解析其class屬性中設定的驗證規則,並將相應的驗證方法綁定到元素的onblur事件。exB_Email將獲得默認的“必須輸入”和“E-mail格式”驗證。
但是,這種做法有兩個缺點,一個是會使得HTML看上去很怪異,並且無法設定具體每個字段的錯誤提示信息。因此,需要採用第二種方法。
第二種方法需要將js代碼寫成:
window.addEvent("domready", function() {
var exValidatorB = new fValidator("exB");
});
通過代碼顯式地註冊一個驗證規則。"exB_Name"是字段的id,後面是一個JSON。其中type指定了驗證規則,re是規則正則表達式,msg是提示信息。一下是目前支持的驗證規則,在註冊時需要提供對應的屬性:
required: {type: "required", re: /[^.*]/, msg: "This field is required."},
alpha: {type: "alpha", re: /^[a-z ._-]+$/i, msg: "This field accepts alphabetic characters only."},
alphanum: {type: "alphanum", re: /^[a-z0-9 ._-]+$/i, msg: "This field accepts alphanumeric characters only."},
integer: {type: "integer", re: /^[-+]?/d+$/, msg: "Please enter a valid integer."},
real: {type: "real", re: /^[-+]?/d*/.?/d+$/, msg: "Please enter a valid number."},
date: {type: "date", re: /^((((0[13578])|([13578])|(1[02]))[//](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[//](([1-9])|([0-2][0-9])|(30)))|((2|02)[//](([1-9])|([0-2][0-9]))))[//]/d{4}$|^/d{4}$/, msg: "Please enter a valid date (mm/dd/yyyy)."},
email: {type: "email", re: /^[a-z0-9._%-]+@[a-z0-9.-]+/.[a-z]{2,4}$/i, msg: "Please enter a valid email."},
phone: {type: "phone", re: /^[/d/s ().-]+$/, msg: "Please enter a valid phone."},
url: {type: "url", re: /^(http|https|ftp)/:////[a-z0-9/-/.]+/.[a-z]{2,3}(:[a-z0-9]*)?//?([a-z0-9/-/._/?/,/'/////+&%/$#/=~])*$/i, msg: "Please enter a valid url."},
confirm: {type: "confirm", msg: "Confirm Password does not match original Password."},
fValidator.js很容易理解,大家可以根據自己的需要對其進行一些改寫。雖然fValidator和iMask並不能替代服務器端驗證和Ajax驗證,但是它們確實可以使我們快速地構建起具有良好用戶體驗的客戶端驗證。因此,我覺得fValidator+iMask+Ajax+服務器端驗證,將是一個完美而完整的驗證體系。