jQuery validate - how to validate one field with two XOR rules

前端 未结 1 1502
终归单人心
终归单人心 2021-01-14 09:01

I have one field which can contain email or mobile (in my case mobile is 8 digits). I already tried two approaches (both examples doesn\'t work, because \'element\' do not h

相关标签:
1条回答
  • 2021-01-14 09:14

    How about the following validation method...

    $.validator.addMethod("xor", function(val, el, param) {
        var valid = false;
    
        // loop through sets of nested rules
        for(var i = 0; i < param.length; ++i) {
            var setResult = true;
    
            // loop through nested rules in the set
            for(var x in param[i]) {
                var result = $.validator.methods[x].call(this, val, el, param[i][x]);
    
                // If the input breaks one rule in a set we stop and move
                // to the next set...
                if(!result) {
                    setResult = false;
                    break;
                }
            }
    
            // If the value passes for one set we stop with a true result
            if(setResult == true) {
                valid = true;
                break;
            }
        }
    
        // Return the validation result
        return this.optional(el) || valid;
    }, "The value entered is invalid");
    

    Then we could set up the form validation as follows...

    $("form").validate({
      rules: {
        input: {
          xor: [{
            digits: true,
            rangelength: [8, 8]
          }, {
            email: true
          }]
        }
      },
      messages: {
        input: {
          xor: "Please enter a valid email or phone number"
        }
      }
    });    
    

    See it in action here http://jsfiddle.net/eJdBa/

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