Reputation: 429
I want users signing up on my site to choose passwords that include:
At least one digit. But these are the minimum requirements. They can include any characters such as @,#,&, etc. as long as these requirements are met. I have the following regex:
/^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)\w{8,20}$/
But it doesn't match other characters asides those in the requirements listed above. I want to be able match a password that can contain any character but still meet the conditions above. How do i do this?
Upvotes: 2
Views: 1808
Reputation: 93725
Don't do it all in one regex. It is far more readable and maintainable to make each validation its own check.
$passes =
preg_match( '/[A-Z]/', $pw ) && # uppercase char
preg_match( '/[a-z]/', $pw ) && # lowercase char
preg_match( '/\d/', $pw ) && # digit
(strlen($pw) > 8); # at least 8 characters
Upvotes: 2
Reputation: 44841
This will do what you want:
/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$/
Explanation:
^
matches the start of the string(?=.*[A-Z])
requires an uppercase character(?=.*[a-z])
requires a lowercase character(?=.*\d)
requires a digit.{8,}
requires minimum length of 8.Note: Unlike anubhava's answer, this allows for whitespace characters. If you don't want whitespace, use \S
as suggested by anubhava.
Edit: Per the excellent point by @ridgerunner in the comments, here is a slightly more efficient regex:
/^(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=\D*\d).{8,}$/
This version avoids the lazy .*
expression, which wastes time in testing the overall regex in this context.
Upvotes: 2
Reputation: 785491
Use this regex:
/^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)\S{8,20}$/
I have used \S
(any non space character) instead of \w
(word character that means [a-zA-Z0-9_]
)
Upvotes: 1