Adorablepolak
Adorablepolak

Reputation: 157

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:

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");

Upvotes: 1

Views: 6800

Answers (2)

user6906742
user6906742

Reputation: 21

$.validator.addMethod("pwcheck", function(value) {

      return /^[a-zA-Z0-9!@#$%^&*()_=\[\]{};':"\\|,.<>\/?+-]+$/.test(value)
       && /[a-z]/.test(value) // has a lowercase letter
       && /\d/.test(value)//has a digit
       && /[!@#$%^&*()_=\[\]{};':"\\|,.<>\/?+-]/.test(value)// has a special character
      },"must consist  lowercase letter, number and special characters");

Upvotes: 2

Danilo
Danilo

Reputation: 2686

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/

Upvotes: 5

Related Questions