Adorablepolak Adorablepolak - 2 months ago 13
jQuery Question

Issue with regex for special characters in additional method jquery validate

I have different rules for password validation. Most of them are working fine but the one for special characters is kind of tricky. The rule says: The password must contain at least one special character (from a list of special characters). I created the additional method for jquery validate to handle this but for some reason characters outside of the list are treated as valid.

For example:


  • 654321Ab/ is valid as / is an accepted special character

  • 654321Ab/° must not be valid as ° is not a valid special character but now it is treated as correct



This is my jsfiddle: http://jsfiddle.net/o6L3s14c/

My script for the additional method:

$.validator.addMethod("pwcheckspechars", function (value) {
return /[!@#$%^&*()_=\[\]{};':"\\|,.<>\/?+-]/.test(value)
}, "The password must contain at least one special character");

Answer

The rule you report checks whether the string contains at least one of your special characters. Both the strings you mention are compliant with this rule (both contain /).

The fact that the second string contains an additional character which is not included in your rule does not change the validity of your test (/ is still there).

You could add another validation method to check that your string contains only allowed characters, something along this line:

/^[a-zA-Z0-9!@#$%^&*()_=\[\]{};':"\\|,.<>\/?+-]+$

which can be interpreted as:

START (a-Z, A-Z, 0-9 or some special characters) one or more times END

Example: http://jsfiddle.net/o6L3s14c/4/