Joe Essey
Joe Essey

Reputation: 3527

Regex for jquery validation

I've got the following addMethod for jquery validation:

    $.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
        "Invalid number of characters entered."
    );

And in my field I want to validate that the user enters 7, 9, 12, 13, or 15 chars, I can't get the regex to work. I've tried each of the following with their corresposing results:

"......." - Validates that 7 chars are entered

".......| ........." - Validates that 7 chars are entered but claims error when 9 are entered.

'/^([a-z0-9]{7,}|[a-z0-9]{9,})$/' - Fails to validate anything.

I realize there are plenty of resources out there but this is my first use of regex and I can't seem to put the right combination together. Please help if you see a solution. Thanks.

Upvotes: 0

Views: 665

Answers (1)

pajaja
pajaja

Reputation: 2202

You can specify exact number of characters by .{n}, where n is the number of characters that . matches. {n,} notation you used in third example means n or more. Combining that with your examples you can build a regexp that looks like ^(.{7}|.{9}|.{12}|.{13}|.{15})$.

Upvotes: 1

Related Questions