Jquery validate驗證表單時多個name相同的元素只驗證第一個的問題

下面蒐集了五種方法,主要仍是前兩個提供瞭解決方案,第三種須要修改jQuery源碼:

修復jquery.validate插件中name屬性相同(如name=’a[]‘)時驗證的bug

使用jquery.validate插件http://jqueryvalidation.org/,當節點的name相同時候,腳本特地忽略剩餘節點,致使全部相關節點的errMsg都顯示在第一個相關節點上。這個bug在動態生成表單時候影響比較大。javascript

經過查詢資料,找到一個解決方案:css

http://stackoverflow.com/questions/931687/using-jquery-validate-plugin-to-validate-multiple-form-fields-with-identical-namhtml

具體內容爲java

$(function () {
if ($.validator) {
    //fix: when several input elements shares the same name, but has different id-ies....
    $.validator.prototype.elements = function () {


        var validator = this,
            rulesCache = {};


        // select all valid inputs inside the form (no submit or reset buttons)
        // workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved
        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);


            // select only the first element for each name, and only those with rules specified
            if (elementIdentification in rulesCache || !validator.objectLength($(this).rules()))
                return false;


            rulesCache[elementIdentification] = true;
            return true;
        });
    };
}
});

在頁面上引入以上代碼,而後給相關節點加上id屬性,當name屬性相同時候會以id屬性來驗證jquery

-------------------------------------------------------------------------------------------

用下面這種方式應該能解決:(http://stackoverflow.com/questions/2589670/using-jquery-validate-with-multiple-fields-of-the-same-name)
$(function(){ $("#myform").validate(); $("[name=field]").each(function(){ $(this).rules("add", { required: true, email: true, messages: { required: "Specify a valid email" } }); }); }); ---------------------------------------------------------------------------------- jquery.validate.js 相同name的多個元素只能驗證第一個元素的解決辦法
動態生成的相同name的元素驗證只會取第一個.
很惱火的問題.只有將jquery.validate.js中的對相同name的元素判斷註釋掉.
可是不知道會不會引發其餘地方的BUG
但願之後jquery.validate.js能作針對元素ID進行驗證而不單單針對元素name驗證.



方法:
將484行的代碼註釋掉便可

  // select only the first element for each name, and only those with rules specified if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) { return false; }ide


註釋成

  // select only the first element for each name, and only those with rules specified /*if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) { return false; }*/ui

-----------------------------------------------------------------------------------------------------------------------------------------




<html>
 <head>
 <link href="style.css" rel="stylesheet">
<script src="assets/js/jquery-1.7.1.min.js"></script>
<script src="assets/js/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#contact-form').validate();

$(":text").each( function(){ 
 $(this).rules( "add", {
 required:true,
 minlength: 2
 })
 });

}); 

</script>
 </head>
 <body>
 <form action="" id="contact-form" class="form-horizontal"> 
 <p>
 <input type="text" name="test_a" id="a"><br>
 <input type="text" name="test_a" id="b"><br>
 <input type="text" name="test_a" id="c"><br>
 <button type="submit" class="btn btn-primary btn-large">Submit</button>
 <button type="reset" class="btn">Cancel</button> 
 </form> 
 </body>
</html>
這個表單的input 是隨機生成的,因此name都是相同的,我如今要用jquery.validate.js來驗證輸入,如今只校驗了第一id=‘a' 的,怎麼讓我驗證全部的?

你這麼寫實際上是添加驗證成功的了,驗證會被執行,只是submit的時候不是你想要的效果。

你能夠試試,輸入第一個框後,在第二個框裏點一下不輸入再點到第三個框。
能夠看到驗證的邏輯被執行了。

分析一下緣由:
 jquery.validate 這個插件在生成rules的時候是按name來生成的,也就是說,你的表單其實只添加了一條驗證rule:就是對name=test_a的字段作非空和最小長度驗證。

當輸入框失去焦點時會觸發這條規則,由於每一個input的name都是test_a,能夠命中rules中的規則

當submit的時候,一樣會調用{'test_a': { required:true, minlength: 2}}這條規則, 只不過這條規則會被經過,由於已經有一個test_a字段達到了規則的要求。
追問
那怎麼實現submit的時候所有校驗呢?
回答
修改input的name, 動態生成不一樣的name
追問
我使用class的方式仍是隻檢驗一個啊?求解
回答
嗯,我也試了,是不行。因此建議修改name, 或者不用jq的插件
---------------------------------------------------------------------------------------------------------------------------------------------

function validate()
{
       var result=true;
      $("input[name='你定義的name']").each(
                  function(){
                 if($(this).val()=="")
                                             {
                            alert("請輸入");
                            $(this).focus();
                            result=false;
                            return;
                 }        
      }
);
      return result;
}






參考文章:http://blog.csdn.net/zoutongyuan/article/details/28094565
  

關注公衆號,分享乾貨,討論技術

相關文章
相關標籤/搜索