Question

I'm trying to test a string using jquery.validator and xregexp but I need to be able to dynamically set a flag for case insensitivity. Problem is I don't know how to send the flags for my xregexp to the addmethod using a param. Here is what my addmethod currently looks like:

$.validator.addMethod(
    "regex",
    function(value, element, regexp) {
        var re = new XRegExp(regexp);
        return this.optional(element) || re.test(value);
    },
    "Please check your input."
);

And here is my call to it:

webAddr: {
    regex: '^(http(s)?:\/\/)?(([a-z]+[a-z0-9-\\.]*)\\.)+[a-z]{2,}$\\i',
    maxlength: 256,
    minlength: 4
},

My problem is the \\i. I want to include it but according to the docs you have to include it as a separate param using this format:

XRegExp(regexp, flags);

How do I do I pass that dynamic using jquery.validator?

PS: The reason I'm using xregexp and not something else is because I need true UTF-8 support elsewhere in my code, so I try to stick to using it for everything to help me get more proficient with it.

Était-ce utile?

La solution

Pass an object for regex to separate the regex proper from the flags:

webAddr: {
    regex: {regex: '^(http(s)?:\/\/)?(([a-z]+[a-z0-9-\\.]*)\\.)+[a-z]{2,}$', 
            flags:'i'},
    maxlength: 256,
    minlength: 4
},

(I've changed the flag from '\\i' to 'i' because I've never heard of '\\i' as a flag.)

And modify your validation code like this:

$.validator.addMethod(
    "regex",
    function(value, element, param) {
        var re = new XRegExp(param.regex, param.flags);
        return this.optional(element) || re.test(value);
    },
    "Please check your input."
);

I've not tested this code so watch out for typos.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top