-2

I am trying to validate if a new user account's password is matching these criterias:

  • Between 8-30 characters long
  • Contains at least 1 lowercase letter (a-z)
  • Contains at least 1 uppercase letter (A-Z)
  • Contains at least 1 of the following special characters: _-!#*@&

I have a function like this:

function validPassword($str) {
    return preg_match("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_-!#*@&])[A-Za-z\d_-!#*@&]{8,30}$", $str);
}

But I am getting an error. It should return "true" for this password for example: HelloWorld123!

But instead it is returning false. Any idea what may be wrong?

if (validPassword($password) == true) {
  // good password
}

2 Answers2

1

You forgot to escape '-', and delimiters...

function validPassword($str) {
  return preg_match("/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\-!#*@&])[A-Za-z\d_\-!#*@&]{8,30}$/", $str);
}
dimooski
  • 36
  • 4
0

Your regex is having errors which is why there is no match in the first place.

Change your regex to this:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\-!#*@&])[A-Za-z\d_\-!#*@&]{8,30}$

Have a look at your regex in action here: https://regex101.com/r/ogPPeb/1

shuberman
  • 1,416
  • 6
  • 21
  • 38