2013-10-14 37 views
1

我有很多關於此的搜索,但還沒有找到任何解決方案。我想在JQuery驗證中驗證多個命名文件輸入和下拉列表。在jQuery驗證多個「數組命名」文件輸入和下拉驗證

<td> <input type="text" class="times" name="times[]" /> </td> 
</tr> 
<tr> 
<td> <input type="text" class="times" name="times[]" /> </td> 
</tr> 
<tr> 
<td> <input type="text" class="times" name="times[]" /> </td> 
</tr> 

我已經添加JQuery驗證這樣的代碼:

$("#formname").validate(
    { 
    rules:{ 
     times:{required:true, digits:true} 
    }} 
    ); 

但其僅在驗證第一輸入和顯示錯誤信息有第二或第三個輸入字段只有是否進入與否。

我不想改變這個「times []」的名字,因爲功能取決於這個。只有我想使用JQuery驗證進行驗證。

有沒有這方面的技巧?

任何幫助,將不勝感激。

謝謝

回答

1

插件不能很好地處理同名的字段。這是我在應用程序中解決它的方式。

我給所有的重複字段不同的名稱,並將驗證方法名稱放在類中。

<td> <input type="text" class="times required digits" name="times[0]" /> </td> 
</tr> 
<tr> 
<td> <input type="text" class="times required digits" name="times[1]" /> </td> 
</tr> 
<tr> 
<td> <input type="text" class="times required digits" name="times[2]" /> </td> 
</tr> 

你可以用代碼提交這樣之前刪除索引:

$("#formname").validate({ 
    ... 
    submitHandler: function(form) { 
     $(form).find(":input[name*='[']").each(function() { 
      this.name = this.name.replace(/\[\d+\]/, '[]'); 
     } 
     form.submit(); 
    } 
}); 
+0

謝謝,但我要爲我所有輸入字段唯一的名稱。其實這個表格非常龐大,很多輸入和下拉的名字都是這樣的,所以我不能改變這個名字。是否有可能通過傳遞一些指標到Jquery驗證? – Sky

+0

你可以讓你的提交處理器遍歷所有的字段,並從括號中刪除數字 - 這就是我所做的。 – Barmar

+0

基本問題是插件期望名稱是唯一的。它使用名稱作爲內部表中的關鍵字。如果有重複,它將驗證所有這些,但始終將錯誤消息放在第一個旁邊。 – Barmar