jQuery Form Validation plugin with multiple rules

后端 未结 1 964
旧时难觅i
旧时难觅i 2021-01-21 06:13

I\'m using the jQueryValidation plugin. Problem: I would like to use multiple pattern rules within for one input field. E.g.:

$(\"form\").valida         


        
相关标签:
1条回答
  • 2021-01-21 06:58

    You cannot use the same key:value pair twice since the second instance will override the first.

    You have a couple of options.

    • Combine the two regex expressions into one. One method will be declared with one error message. So instead of using the pattern rule/method from the additional-methods.js file, you will create your own custom rule using the .addMethod() method.

    • Instead of combining the regex patterns, use the pattern rule once and create a new second rule using .addMethod().

    See: http://jqueryvalidation.org/jQuery.validator.addMethod/


    I'd create a custom method dedicated to each regex pattern and give it a semantically relevant name, something like 'email', 'phone', 'alphanumeric', 'IP', etc. (This is also the same way all the regex evaluated rules are handled internally by this plugin.)

    jQuery.validator.addMethod("foo", function(value, element) {
        return this.optional(element) || /^[A-Za-z0-9\w]{4,20}/.test(value);
    }, "Your entered data is not foo");
    
    jQuery.validator.addMethod("bar", function(value, element) {
        return this.optional(element) || /^[\d\w\xC4\xD6\xDC\xE4\xF6\xFC\xDF]*$/.test(value);
    }, "Your entered data is not bar");
    

    Declared like this...

    "password": {
        required: true,
        foo: true,
        bar: true
    }
    
    0 讨论(0)
提交回复
热议问题