You can follow @Thomas's solution to define symbols as all non-word chars \W
, but be aware that this includes whitespace. If a user has a newline char in their password, they're almost certain to be locked out.
For passwords, it's worth going through the work of describing exactly what characters you want to allow. If you want to use tilde ~
or period .
, just add them to your character classes in the regex as @anubhava suggested.
"^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$"
// ^ ^
// \__add them here __/_________
// | | | |
"^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&~\.])[A-Za-z\d$@$!%*#?&~\.]{8,}$"
To use regexes responsibly, our goal should be to understand what's going on under the hood. Here's a walk-through of how the regex you're using works.
^
// From the beginning of your string
(?=.*[A-Za-z])
// Look ahead (?= )
// any number of chars .*
// Until you find an alpha character [A-Za-z]
(?=.*\d)
// Look ahead (?= )
// any number of chars .*
// Until you find a digit \d
(?=.*[$@$!%*#?&])
// Look ahead (?= )
// any number of chars .*
// Until you find one of these chars [$@$!%*#?&]
[A-Za-z\d$@$!%*#?&]{8,}
// Find any of these characters [A-Za-z\d$@$!%*#?&]
// 8 or more times {8,}