-1

I am new to regex and want to verify a string which contains user password and that should contains lowercase, uppercase, number and special character and must have length of 8 characters and maximum of 20 so how how can I limit this regex between 8 and 20 characters here is the regex :

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$
zeeeuu
  • 19
  • 4
  • change `.+` to `.{8,20}` in the end of your regex – Pushpesh Kumar Rajwanshi Apr 18 '19 at 09:18
  • It's quite a nonsense to limit passwords to 20 char (the more there is, the more it's secure, kind of).. also, this kind of rules is now officially discouraged, as they wrongly make people believe it increases security when it doesn't. https://xkcd.com/936/ – Kaddath Apr 18 '19 at 09:21

2 Answers2

1

At the end of your regular expression you have the three symbols .+$

This means:

  • any character (.)
  • one or more (+)
  • end of string ($).

You want to target the one or more (+) and change it into a limit with {from, to} syntax.

So for 8-20 chars use {8, 20} instead of +:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).{8,20}$

Do note that is is not good practice to limit password length. Passwords should always be hashed and have a fixed length in the database.

Daniel
  • 10,641
  • 12
  • 47
  • 85
0

The .+ in the end of that regex indicate that you want those characters "at least once"

Change it to .{8, 20} in order to restrict the character numbers between 8 and 20

Thelt
  • 81
  • 5