Search code examples
jqueryregexjquery-validateregex-negationnegate

Regex and jquery validate. Negate expression


I'm working on a addition method for the jquery validate plugin which must detect if 3 or more consecutive identical characters are entered, and prompt a message. To do so I need to negate a regex expression. This is my method:

$.validator.addMethod("pwcheckconsecchars", function (value) {
    return /(.)\1\1/.test(value) // does not contain 3 consecutive identical chars
}, "The password must not contain 3 consecutive identical characters");

The code above shows the error message when no consecutive identical characters have been entered, so I need to negate the expression /(.)\1\1/ so that it only appears when the error has been made.

This jsfiddle shows my code so far: http://jsfiddle.net/jj50u5nd/3/

Thanks


Solution

  • As stated by Pointy in the comments, use a ! character to negate or invert the result.

    $.validator.addMethod("pwcheckconsecchars", function (value) {
        return !/(.)\1\1/.test(value); // does not contain 3 consecutive identical chars
    }, "The password must not contain 3 consecutive identical characters");
    

    Enter a "AAAa1" into the demo below, it satisfies enough of the other rules to demonstrate this particular method is working.

    DEMO: http://jsfiddle.net/jj50u5nd/6/