Arkhall Arkhall - 6 months ago 20
Javascript Question

Regex - At least 1 number, 1 letter, 1 special character and at least 3 characters

I wanna test my own regex in order to understand how can i use it and create my custom regex.

I tried this one :

^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]){3}$


(?=.*\d)
=> at least 1 number.
(?=.*[a-zA-Z])
=> at least 1 letter.
(?=.*[\W_])
=> at least 1 special character.
{3}
=> at least 3 characters.

Unfortunately, it doesn't work, but i want at least 1 number, 1 letter and 1 special character, and at least 3 characters in my input. When the user types those 3 types of characters, my message disappears because the regex is correct ^^

Sorry for my bad english, I can give you more details if you want and thank you for the help :)

Have a nice day :)

Answer

The problem is that your {3} quantifier applies to your last look-ahead, which is nonsensical : it means that at the start of the text, you must match 3 times the look-ahead, which is a given if it matches once since lookaround are 0-width matches.

You could use the following :

^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]).{3,}$

which specifies, aside from your existing look-aheads, that at least 3 characters must be matched.

If you just test the string, it would also be enough to match

^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\W_]).{3}

without an end anchor : you match 3 characters, and stop matching what follows since your requisites are met.

Comments