-2

I have refered, Srinivas's answer to make password validation. The regex for minimum 8 character, 1 number, 1 alphabet and 1 special character is

"^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$"

With this regex, i can use only the following special characters. $@$!%*#?& . So if I use dheepan~123 or dheepan.123 the vaildation fails. How can I allow all the special characters?

Community
  • 1
  • 1
JPS
  • 2,730
  • 5
  • 32
  • 54
  • 1
    *"all the special characters"* ? Define them and you have your answer. – Denys Séguret Jun 28 '16 at 12:01
  • 1
    That means you didn't understand given solution. Just add those special characters to your character class. – anubhava Jun 28 '16 at 12:02
  • add them in [$@$!%*#?&]. when adding dot remember to give slash ( \. ). With "~" - I dont know if slash is required but you can try with and without. – Michał M Jun 28 '16 at 12:08
  • @All, Thanks for your suggestion to add it to the character class. But, I did not want to specify each one in particular. I just wanted to know if there is a general way. May be I've not phrased my question properly:) I got the answer from Thomas Ayoub anyway. – JPS Jun 28 '16 at 12:12

2 Answers2

1

You can allow all special char by using \W but I'm not sure you really want to do this... Anyway:

^(?=.*[A-Za-z])(?=.*\d)(?=.*[\W])[\w\W]{8,}$
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
0

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,}
Cam
  • 921
  • 7
  • 13