I need to validate a password with these rules:
The following expression matches all but the last requirement. What can I do with the last one?
((?=.*\d)(?=.*[A-z]).{6,20})
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
I'm not completely sure I have this right, but since your last requirement is "Can contain the following characters: !@#$%&*" I am assuming that other special characters are not allowed. In other words, the only allowed characters are letters, digits, and the special characters !@#$%&*.
If this is the correct interpretation, the following regex should work:
^((?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9!@#$%&*]{6,20})$
Note that I changed your character class [A-z]
to [a-zA-Z]
, because [A-z]
will also include the following characters: [\]^_`
I also added beginning and end of string anchors to make sure you don't get a partial match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With