javascript – Regex for password must contain at least eight characters, at least one number and lower and upper case letters and special characters


I would answer Peter Mortensen, but I don't have enough reputation.

Its expressions are perfect for each of the minimum requirements specified. The problem with its expressions that don't require special characters is that they don't allow special characters either, so they also impose maximum requirements, which I don't believe the OP asked. Normally, you want to allow your users to make their password as strong as they want; why restrict strong passwords?

Thus, its expression "at least eight characters, at least one letter and one number":

^(?=.*(A-Za-z))(?=.*d)(A-Za-zd){8,}$

meets minimum requirement, but remaining characters may only be letters and numbers. To allow (but not require) special characters, you should use something like:

^(?=.*(A-Za-z))(?=.*d).{8,}$ to allow all characters

or

^(?=.*(A-Za-z))(?=.*d)(A-Za-zd$@$!%*#?&){8,}$ to allow specific special characters

Likewise, "at least eight characters, at least one uppercase letter, one lowercase letter and one number:"

^(?=.*(a-z))(?=.*(A-Z))(?=.*d)(a-zA-Zd){8,}$

meets this minimum requirement but only authorizes letters and numbers. Use:

^(?=.*(a-z))(?=.*(A-Z))(?=.*d).{8,}$ to allow all characters

or

^(?=.*(a-z))(?=.*(A-Z))(?=.*d)(A-Za-zd$@$!%*?&){8,} to allow specific special characters.