我想通过添加规则和消息的jquery验证来验证复选框。我这样做了,但有些地方我错误地认为代码不起作用。
我希望用户必须至少在表单提交前选择一个复选框。
<form id="myform">
<input type="checkbox" name="test[]" class="clschk" />x
<input type="checkbox" name="test[]" class="clschk"/>y
<input type="checkbox" name="test[]" class="clschk"/>z
<input type="submit" />
</form>
<a id="docs" href="http://docs.jquery.com/Plugins/Validation" target="_blank">Validation Documentation</a>
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
'.clschk': {
required: true,
maxlength: 2
}
},
messages: {
'.clschk': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
答案 0 :(得分:1)
问题仅仅是因为rules
对象的键必须等于元素的name
属性,而不是它的选择器。试试这个:
$('#myform').validate({ // initialize the plugin
rules: {
'test[]': { // note here
required: true,
maxlength: 2
}
},
messages: {
'test[]': { // and here
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
},
submitHandler: function(form) {
alert('valid form submitted');
return false; // for demo
}
});
答案 1 :(得分:0)
您可以使用 addClassRules 方法添加基于类的验证消息,然后您可以通过以下代码覆盖默认消息
$。validator.addMethod(&#34; cRequired&#34;,$ .validator.methods.required,&#34;您必须至少检查一个框&#34;); < / p>
$(document).ready(function () {
$.validator.addClassRules({
clschk:{
cRequired: true,
cmaxlength: 2
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
$('#myform').validate();
$.validator.addMethod("cRequired", $.validator.methods.required,"You must check at least 1 box");
$.validator.addMethod("cmaxlength", $.validator.methods.maxlength,"You must check at least 1 box");
});
更新小提琴 - http://jsfiddle.net/Nbcj9/398/