我们可以使用带有jqueryvalidation器的通配符

当元素名称没有修复时,我们可以在那里使用通配符来指定名称。

下面的代码将工作

 $(document).ready(function () { $('#myform').validate({ rules: { $("[name^=test]"): { required: true, maxlength: 1 } }, messages: { $("[name^=test]"): { 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 } }); });    
x y z

我认为实现这一目标的最佳方法是考虑:

  1. validate(规则和消息)的参数是json对象。
  2. 如果json对象必须具有动态内容,则可以在运行时创建它
  3. 您需要一个自定义规则来检测所选复选框的最大数量
  4. 你需要定义一个函数来定义相应的错误信息(最大值不能写在多个地方,以避免混淆和副作用)。

因此,您的问题的可能解决方案可以是:

 // global variable to save the validator object var validator; // a new rule to test if the selected checkboxes are more than the max or less than one $.validator.addMethod('checkboxMax', function (value, elem, param) { var cacheCheckedElements = $('[name^=test]:checked'); if (cacheCheckedElements.length < 1 || cacheCheckedElements.length > param.max) { return false; } else { validator.resetForm(); return true; } }); $(function () { // on ready: create the two json object: rules and messages var myRules = {}; var myMessages = {}; $('[name^=test]').each(function (index, element) { myRules[element.name] = { checkboxMax: { max: 2 } }; myMessages[element.name] = { checkboxMax: function(params, element) { return 'Check no more than ' + params.max + ' boxes '; } }; }); // use the previous fields (myRules and myMessages) as arguments validator = $('#myform').validate({ rules: myRules, messages: myMessages, submitHandler: function (form) { // for demo alert('valid form submitted'); // for demo return false; // for demo } }); }); 
   
x y z