Can we use wildcard with jquery validator

前端 未结 1 830
囚心锁ツ
囚心锁ツ 2021-01-23 14:32

when element name is not fixed then can we use wild card there for specifying name.

below code will work



        
1条回答
  •  故里飘歌
    2021-01-23 14:59

    I assume the best way to achieve this goal is to consider:

    1. the parameters of validate (rules and messages) are json objects.
    2. a json object can be created at runtime if it must have dymanic content
    3. you need a custom rule to detect the max number of selected check boxes
    4. you need to define a function to define the corresponding error message (the max value cannot be written in more than one place to avoid confusion and so side effects).

    So, a possible solution for your problem can be:

    // 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

    0 讨论(0)
提交回复
热议问题