Reputation: 61463
I'm working on a password validation screen and the requirement is to have at least one symbol such as the ones listed below.
How should I escape them so it works correctly under Javascript?
//validate symbol
if (pswd.match(/`~!@#$%^&*()_+=-\][{}\;':"<>?,/./)) {
$('#symbol').removeClass('invalid').addClass('valid');
} else {
$('#symbol').removeClass('valid').addClass('invalid');
}
Upvotes: 0
Views: 142
Reputation: 56809
I'm not sure the characters that you want to match, since the original string is quite messy. Check whether this is all the characters you want:
"we?dn^~!@#$%^&*()_+-={dsfs}sf[]\\|:\";',./?><".match(/[`~!@#$%^&*()_+=\]\[{};':"<>?,\/.-]/g)
>> ["?", "^", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "+", "-", "=", "{", "}", "[", "]", ":", """, ";", "'", ",", ".", "/", "?", ">", "<"]
For the sake of clarity, this is the regex:
/[`~!@#$%^&*()_+=\]\[{};':"<>?,\/.-]/
EDIT
If you want to include \
and |
use this regex:
/[\\`~!@#$%^&*()_+=\]\[{};':"<>?,\/.|-]/
Upvotes: 0
Reputation: 104780
The slashes and right-square-bracket are the only ones that need to be escaped in a character group-as long as the hyphen is not between two characters.
if(/[/`~!@#$%^&*()_+=[{};':"<>?,.\/\]-]/.test(pswd) ){
Upvotes: 1
Reputation: 16039
Use this instead:
if (pswd.match(/[^A-Za-z0-9]+/)) {
It matches any text that contains at least one character that is not in the list [A-Za-z0-9]
Upvotes: 2