Reputation: 8086
I not getting the desired effect from a script. I want the password to contain A-Z, a-z, 0-9, and special chars.
So I want to force the user to use at least 2 digits and at least 2 special chars. Ok my script works but forces me to use the digits or chars back to back. I don't want that. e.g. password testABC55$$ is valid - but i don't want that.
Instead I want test$ABC5#8 to be valid. So basically the digits/special char can be the same or diff -> but must be split up in the string.
PHP CODE:
$uppercase = preg_match('#[A-Z]#', $password);
$lowercase = preg_match('#[a-z]#', $password);
$number = preg_match('#[0-9]#', $password);
$special = preg_match('#[\W]{2,}#', $password);
$length = strlen($password) >= 8;
if(!$uppercase || !$lowercase || !$number || !$special || !$length) {
$errorpw = 'Bad Password';
Upvotes: 4
Views: 10823
Reputation: 11
This will do the trick. Look ahead is nice for this...
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d.*\d)(?=.*\W.*\W)[a-zA-Z0-9\S]{4,}$/
EXPLAINED in pieces below
Look ahead/require for a lower case:
(?=.*[a-z])
Look ahead/require an uppercase:
(?=.*[A-Z])
Look ahead/require 2 digits:
(?=.*\d.*\d)
Look ahead/require any 2 non-word chars (same as [^a-zA_Z0-9_]):
(?=.*\W.*\W)
Entire password must contain a minimum of 4, a maximum is not defined, and only alpha numeric and special chars (non white-space):
[\S]{4,}
Upvotes: 0
Reputation: 1789
For matching length of string including special characters:
$result = preg_match('/^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[^A-Za-z\d])[\s\S]{6,16}$/', $string);
Answer explained: https://stackoverflow.com/a/46359397/5466401
Upvotes: 0
Reputation: 43673
Using "readable" format (it can be optimized to be shorter), as you are regex newbie >>
^(?=.{8})(?=.*[A-Z])(?=.*[a-z])(?=.*\d.*\d.*\d)(?=.*[^a-zA-Z\d].*[^a-zA-Z\d].*[^a-zA-Z\d])[-+%#a-zA-Z\d]+$
Add your special character set to last [...]
in the above regex (I put there for now just -+%#).
Explanation:
^ - beginning of line/string
(?=.{8}) - positive lookahead to ensure we have at least 8 chars
(?=.*[A-Z]) - ...to ensure we have at least one uppercase char
(?=.*[a-z]) - ...to ensure we have at least one lowercase char
(?=.*\d.*\d.*\d - ...to ensure we have at least three digits
(?=.*[^a-zA-Z\d].*[^a-zA-Z\d].*[^a-zA-Z\d])
- ...to ensure we have at least three special chars
(characters other than letters and numbers)
[-+%#a-zA-Z\d]+ - combination of allowed characters
$ - end of line/string
Upvotes: 12
Reputation: 13450
((?=(.*\d){3,})(?=.*[a-z])(?=.*[A-Z])(?=(.*[!@#$%^&]){3,}).{8,})
test$ABC5#8 is not valid because you ask more than 2 digits and spec symbols
A-Z
a-z
0-9 > 2
special chars > 2
string length >= 8
Upvotes: 1