validate驗證表單時多個name相同的元素的解決辦法


使用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"
       }
     });   
   });
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM