Skip to content

PHP: Validate passwords with regular expression

Last updated on November 23, 2022

Today’s post is about password validation in PHP using Regular Expressions.

Here is the small use full Password Validation function.

function is_valid_password($password) {
    return preg_match_all('$S*(?=S{8,})(?=S*[a-z])(?=S*[A-Z])(?=S*[d])(?=S*[W])S*$');
}

Password Regular Expression Pattern

The whole combination means at least 8 characters string with at least one digit, one upper case letter, one lower case letter, and one special symbol. This regular expression pattern is very useful to implement a strong and complex password.

$S*(?=S{8,})(?=S*[a-z])(?=S*[A-Z])(?=S*[d])(?=S*[W])S*$

Regular Expression Pattern Description

  • $ = beginning of the string
  • S* = any set of characters(non-whitespace character)
  • * =  Zero or more s
  • (?=S{8,}) = of at least length 8
  • (?=S*[a-z]) = containing at least one lowercase letter
  • [a-z] =  It matches any character from lowercase a through lowercase z.
  • (?=S*[A-Z]) = and at least one uppercase letter
  • [A-Z] = It matches any character from uppercase A through uppercase Z.
  • (?=S*[d]) = and at least one number
  • d =  a digit (0-9)
  • (?=S*[W]) =  and at least a special character (non-word characters)
  • $ =  end of the string
0 0 votes
Article Rating
Subscribe
Notify of
guest

6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments