patw 的筆記、生活、隨筆
[jQuery] jQuery plugin: Validation 加上「群組不可有重複值」驗證
jQuery plugin: Validation 是一套很讚的表單前端驗證工具,但少了「群組不可有重複值」這項驗證有些可惜。
什麼時候會用到呢?舉個例來說,表單希望你填入親友A、親友B與親友C 三者的 E-mail,但我們又不希望使用者通通填同一個 E-mail,這時三個欄位就為一個 E-mail 群組,並希望每欄皆為獨立值。
幸好有熱心高手寫了 Validation 的 plugin,可以加掛這項驗證上去,以下來說明怎麼做吧。
原始網址在此
1. 假設您已經加入了 jQuery.js 與 jquery.validate.js,我們接著加入以下的 code:
其中 「Please enter a Unique Value」 是錯誤提示的訊息。
jQuery.validator.addMethod("notEqualToGroup", function(value, element, options) {
// get all the elements passed here with the same class
var elems = $(element).parents('form').find(options[0]);
// the value of the current element
var valueToCompare = value;
// count
var matchesFound = 0;
// loop each element and compare its value with the current value
// and increase the count every time we find one
jQuery.each(elems, function(){
thisVal = $(this).val();
if(thisVal == valueToCompare){
matchesFound++;
}
});
// count should be either 0 or 1 max
if(this.optional(element) || matchesFound <= 1) {
elems.removeClass('error');
return true;
} else {
elems.addClass('error');
}
}, jQuery.format("Please enter a Unique Value."))
2. 表單中需設置為群組的欄位,請都加上 distinctemails 這個 class ,當然,這個名稱是可以依需求更改的。如:
<input type="text" name="email1" class="distinctemails" /> <input type="text" name="email2" class="distinctemails" /> <input type="text" name="email3" class="distinctemails" />
3. 在 validation 的 rules 中加入:
email1: {
email: true,
notEqualToGroup: ['.distinctemails']
},
email2: {
email: true,
notEqualToGroup: ['.distinctemails']
},
email3: {
email: true,
notEqualToGroup: ['.distinctemails']
}
我們加上 notEqualToGroup 這個驗證方法,並指定識別為 distinctemails,也就是步驟 2 中指定的 class。
OK,如此我們便能對這三欄 E-mail 做出不重複值的檢查了。
| Print article | This entry was posted by patw on 2010年八月18日 at 5:15 下午, and is filed under jQuery. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |