Search code examples
phpregexpasswordsalphanumeric

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-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
}

Solution

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

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