使用jquery validator插件時,會碰見頁面中name值相同的情況,此時因為validator驗證規則默認是通過name值驗證的,所以validator驗證不起作用,可在頁面中加入以下代碼:
$(function () { if ($.validator) { $.validator.prototype.elements = function () { var validator = this, rulesCache = {}; return $([]).add(this.currentForm.elements) .filter(":input") .not(":submit, :reset, :image, [disabled]") .not(this.settings.ignore) .filter(function () { var elementIdentification = this.id || this.name; !elementIdentification && validator.settings.debug && window.console && console.error("%o has no id nor name assigned", this); if (elementIdentification in rulesCache || !validator.objectLength($(this).rules())) return false; rulesCache[elementIdentification] = true; return true; }); }; } });
然后給name值相同的節點加入id屬性,此時validator會根據id進行驗證
然后再加入以下代碼即可:
$(function(){ $("#myform").validate(); $("[name=email]").each(function(){ $(this).rules("add", { required: true, email: true, messages: { required: "請輸入正確email" } }); }); });