如何使用jQuery验证验证以下内容。用户必须至少选择以下选项中的一个。
<select name="quantity[adult][seat_a]" class="group-required">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="quantity[adult][seat_b]" class="group-required">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="quantity[adult][seat_c]" class="group-required">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
答案 0 :(得分:0)
要强制选择这些select
元素中的至少一个,您可以使用属于the require_from_group
method的the additional-methods.js
file。
$('#myform').validate({
// other options,
rules: {
"quantity[adult][seat_a]": {
require_from_group: [1, ".group-required"]
},
"quantity[adult][seat_b]": {
require_from_group: [1, ".group-required"]
},
"quantity[adult][seat_c]": {
require_from_group: [1, ".group-required"]
}
},
groups: {
myGroup: "quantity[adult][seat_a] quantity[adult][seat_b] quantity[adult][seat_c]"
}
});
这将创建一个同步&amp;所有三个select
元素上的相同错误消息。使用the groups
option将这些组合成一个和the errorPlacement
option,将生成的消息放入您的布局中。
重要:您还需要每个value
的默认option
的{{1}}为空。否则,插件会认为select
是用户的选择,并且不会验证任何内容。
0
... OR
<select name="quantity[adult][seat_a]" class="group-required">
<option value="">0</option>
....
修改强>
如果您有大量元素,并且不希望在<select name="quantity[adult][seat_a]" class="group-required">
<option value="">Please select...</option>
<option value="0">0</option>
....
中单独声明它们,请在jQuery .validate()
中使用.rules('add')
方法。
.each()
工作演示:http://jsfiddle.net/n1z0Lufw/
此外,使用$('#myform').validate({
// other options,
});
$('.group-required').each(function() {
$(this).rules('add', {
require_from_group: [1, '.group-required']
});
});
选项合并错误消息,无需手动声明每个字段名称...
groups