jQuery validate: How to add a rule for regular expression validation?

前端 未结 13 1288
忘掉有多难
忘掉有多难 2020-11-22 07:41

I am using the jQuery validation plugin. Great stuff! I want to migrate my existing ASP.NET solution to use jQuery instead of the ASP.NET validators. I am m

相关标签:
13条回答
  • 2020-11-22 08:41

    Extending PeterTheNiceGuy's answer a bit:

    $.validator.addMethod(
            "regex",
            function(value, element, regexp) {
                if (regexp.constructor != RegExp)
                    regexp = new RegExp(regexp);
                else if (regexp.global)
                    regexp.lastIndex = 0;
                return this.optional(element) || regexp.test(value);
            },
            "Please check your input."
    );
    

    This would allow you to pass a regex object to the rule.

    $("Textbox").rules("add", { regex: /^[a-zA-Z'.\s]{1,40}$/ });
    

    Resetting the lastIndex property is necessary when the g-flag is set on the RegExp object. Otherwise it would start validating from the position of the last match with that regex, even if the subject string is different.

    Some other ideas I had was be to enable you use arrays of regex's, and another rule for the negation of regex's:

    $("password").rules("add", {
        regex: [
            /^[a-zA-Z'.\s]{8,40}$/,
            /^.*[a-z].*$/,
            /^.*[A-Z].*$/,
            /^.*[0-9].*$/
        ],
        '!regex': /password|123/
    });
    

    But implementing those would maybe be too much.

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