2012-04-03 87 views
2

我想將複選框的值存儲在數組中,但是我不能使用驗證規則,因爲名稱是selectList[]而不是selectList。我試過id,但似乎規則只綁定到名稱。jquery驗證爲陣列輸入添加規則

HTML:

<input id='sendList' type='checkbox' name='selectList[]' value='$set[ListID]'> 

JS規則:

$("#selectList").validate({ 
     rules: { 
      selectList[]: { 
       required: true, 
       minlength: 1 
      } 
     } 
    }) 

}); 

謝謝

回答

0

爲什麼不換selectList[]引號內:

$("#selectList").validate({ 
    rules: { 
     'selectList[]': { 
      required: true, 
      minlength: 1 
     } 
    } 
}); 

initializing Javascript object property names,它們可以是標識符(您嘗試的方式),數字或字符串。

工作代碼:http://jsfiddle.net/rMgLG/

+2

其實這是一個非工作的答案。 jQuery驗證不允許驗證具有相同名稱的多個字段,因此在上面的答案中,名稱爲「selectList []」的第一個字段將得到驗證,如果您嘗試發佈字段數組,那麼它將不會有太大的幫助。 – jtheman 2013-03-12 14:22:35

+0

它爲我工作..........謝謝!!!!!!!!! – 2016-10-24 15:08:57

2

問題是現成jquery.validate.js只驗證類[]的第一個元素。所以,我們需要修改一下。

在jquery.validate.js,找到一個名爲checkForm功能,我們有如下修改它:

checkForm: function() { 
this.prepareForm(); 
for (var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++) { 
if (this.findByName(elements[i].name).length != undefined && this.findByName(elements[i].name).length > 1) { 
for (var cnt = 0; cnt < this.findByName(elements[i].name).length; cnt++) { 
this.check(this.findByName(elements[i].name)[cnt]); 
} 
} else { 
this.check(elements[i]); 
} 
} 
return this.valid(); 
},