2013-07-19 99 views
1

請考慮下面的jQuery驗證代碼的簡單形式。不知怎的,我仍然(不)與規則的語法出錯,因爲驗證不以這種方式工作(當我檢查了一些關於此主題的stackoverflow上的網站)。如何正確使用數組描述規則?jQuery數組驗證不起作用

請幫助。

代碼:

<form id="myForm" name="myForm" action="" method="post" autocomplete="on"> 
<label class="field2" for="productname[0]"> Product name 1 </label> <input id="productname[0]" type="text" name="productname[0]"> <br> 
<label class="field2" for="productname[1]"> Product name 2 </label> <input id="productname[1]" type="text" name="productname[1]"> <br> 
<input type="submit" name="submitForm" value="Submit Form"> 

<script src="js/jquery-1.10.1.min.js"></script> 
<script src="js/jquery.validate.js"></script> 

<script> 
$(function() { 

    $("#myForm").validate({ 

    rules: { 

      'productname[]': { 
       required:true, 
       minlength: 2, 
       maxlength: 30, 
      } 

      } //rules 
    }); //validate() 

}); //function 
</script> 
</body> 

回答

0

似乎問題在於你的html標記。嘗試修改:

<label class="field2" for="productname[0]"> Product name 1 </label> <input id="productname[0]" type="text" name="productname[]"> <br /> 
<label class="field2" for="productname[1]"> Product name 2 </label> <input id="productname[1]" type="text" name="productname[]"> <br /> 
+0

thnx,這是可行的(!) – Joppo

2

我不知道你的後臺是什麼樣子,但命名域[0]和[1]是不必要的

<label class="field2" for="productname_1"> Product name 1 </label> <input id="productname_1" type="text" name="productname[]"> <br> 
<label class="field2" for="productname_2"> Product name 2 </label> <input id="productname_2" type="text" name="productname[]"> <br> 

上面應該是足夠的,並與驗證工作。服務器很可能會將轉換後的查詢字符串轉換爲數組。

+0

thnx您的評論(!)。但是,當我使用它時,您的代碼似乎不起作用。它在更改名稱值(名稱=「productname_1」,name =「productname_2」)時有效。在我的真實代碼中,我有更多的產品名稱和相關字段進行檢查,這需要編寫大量驗證規則和原因爲什麼我嘗試了陣列?YD1m建議的解決方案似乎可行。 – Joppo