javascript regex for special characters
I'm trying to create a validation for a password field which allows only the a-zA-Z0-9
characters and .!@#$%^&*()_+-=
I can't seem to get the hang of it.
What's the difference when using regex = /a-zA-Z0-9/g and regex = /[a-zA-Z0-9]/
and which chars from .!@#$%^&*()_+-=
are needed to be escaped?
What I've tried up to now is:
var regex = /a-zA-Z0-9!@#\$%\^\&*\)\(+=._-/g
but with no success
Solution 1:
var regex = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g
Should work
Also may want to have a minimum length i.e. 6 characters
var regex = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]{6,}$/g
Solution 2:
a sleaker way to match special chars:
/\W|_/g
\W Matches any character that is not a word character (alphanumeric & underscore).
Underscore is considered a special character so add boolean to either match a special character or _
Solution 3:
What's the difference?
/[a-zA-Z0-9]/
is a character class which matches one character that is inside the class. It consists of three ranges.
/a-zA-Z0-9/
does mean the literal sequence of those 9 characters.
Which chars from
.!@#$%^&*()_+-=
are needed to be escaped?
Inside a character class, only the minus (if not at the end) and the circumflex (if at the beginning). Outside of a charclass, .$^*+()
have a special meaning and need to be escaped to match literally.
allows only the
a-zA-Z0-9
characters and.!@#$%^&*()_+-=
Put them in a character class then, let them repeat and require to match the whole string with them by anchors:
var regex = /^[a-zA-Z0-9!@#$%\^&*)(+=._-]*$/
Solution 4:
You can be specific by testing for not valid characters. This will return true for anything not alphanumeric and space:
var specials = /[^A-Za-z 0-9]/g;
return specials.test(input.val());
Solution 5:
How about this:-
var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,}$/;
It will allow a minimum of 6 characters including numbers, alphabets, and special characters