Password validation

I am trying to check that a password entered contains at least 8 characters of which there should be at least 1 uppercase letter, 1 lowercase letter and 1 numeric digit. I am a numpty with regex. The pattern I’m using in my input form is ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$ but this apparently isn’t valid in preg_match.
Can some kind soul help me out here…

Using which I find very handy for regex experiments, it’s enforcing the mix of charaters, but not the min length.
Maybe borrow something from here?


Thanks, Sam. I have tried the following in a PHP sandbox:

$pattern = "(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$";
$pass = "Richard1";
echo preg_match($pattern, $pass);

and it gives me a Warning: preg_match(): Unknown modifier ‘(’

Edit: Ah! a slash either end fixes that!

Yes, you need those delimiters around the pattern.

1 Like

Hello! The pattern you are using seems correct to check if a password contains at least 8 characters, including at least 1 uppercase letter, 1 lowercase letter and 1 numeric digit. However, you can try adding {8,} to the end of the pattern to specify that the password must have at least 8 characters. The final pattern would look like this: ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{8,}$ . Does this solve the problem?

You contradict yourself. First you say it already checks if there are 8 characters.
But then you modify to specify a rule you say already exists. :thinking:

I am new to this platform, so I was answering the question, but with time I will adapt. Ok.

So for clarity of why you got the message:

PHP Regex patterns begin and end with delimiters. PHP does not regulate what character is used as the delimiter (because maybe you wanna use those slashes in the pattern!) - it assumes the first character in the input is the delimiter. So Gandalf’s pattern -
$pattern = "(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$"
starts with a (.
PHP will then process the pattern from the second character until it registers the end of the pattern by seeing the delimiter again. Anything after that is a Modifier, which are single-character flags to set on the pattern, like g for a Global match. What PHP saw instead was:

$pattern = "(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$"

Where Red is the delimiters, Green is the pattern, and Blue is the modifiers.
It tried to parse the modifiers, found a (, but that isnt a valid modifier character, so it threw the error.


Logic wise, preg’s pattern recognition basically does:

list($pattern,$modifiers) = explode($input[0], substr($input,1), 2);

at the start to figure out what’s what.

Maybe I am missing something, but this seems to work. Lookaheads all the way.

$pattern = '/(?=.{8})(?=.*[a-z])(?=.*[A-Z])(?=.*[1-9])/'
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.