我们可以在 jquery 验证器中使用通配符吗

Can we use wildcard with jquery validator

当元素名称不固定时,我们可以在那里使用通配符来指定名称。

下面的代码可以工作

<script type="text/javascript">
$(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
    }
    });


});
    </script>
</head>
<body> 
<form id="myform" runat="server"> 
<input type="checkbox" id="chk1" name="test_1_p1" class="clschk" />x 
<input type="checkbox" id="chk2" name="test_2_p2" class="clschk"/>y 
<input type="checkbox" id="chk3" name="test_3_p3" class="clschk"/>z 
<input id="age" type="text" name="age" /> <input type="submit" /> 
</form> 
</body> 
</html>

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

  1. 验证的参数(规则和消息)是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
    }
  });
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>

<form id="myform" runat="server">
    <input type="checkbox" id="chk1" name="test_1_p1" class="clschk"/>x
    <input type="checkbox" id="chk2" name="test_2_p2" class="clschk"/>y
    <input type="checkbox" id="chk3" name="test_3_p3" class="clschk"/>z
    <input id="age" type="text" name="age"/> <input type="submit"/>
</form>