Skip to content
Advertisement

PHP – Password RegEx requirements

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-zd_-!#*@&]{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
}

Advertisement

Answer

You forgot to escape ‘-‘, and delimiters…

function validPassword($str) {
  return preg_match("/^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[_-!#*@&])[A-Za-zd_-!#*@&]{8,30}$/", $str);
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement