Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 570
Alon Avatar asked Sep 15 '13 12:09

Alon


2 Answers

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 
like image 186
Ed Heal Avatar answered Sep 20 '22 14:09

Ed Heal


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 _

like image 41
TITO Avatar answered Sep 18 '22 14:09

TITO