0

I am not clear with regular expression of php. I would like to validate password with below rules:

  • Password contain at least 8 characters
  • Password contain at least 1 letter
  • Password contain at least 1 digit

Could anyone help me?

user2861903
  • 43
  • 1
  • 5

3 Answers3

2
public function checkPassword($pwd, &$errors) {
$errors_init = $errors;

   if (strlen($pwd) < 8) {
      $errors[] = "Password too short!";
   }

   if (!preg_match("#[0-9]+#", $pwd)) {
      $errors[] = "Password must include at least one number!";
   }

   if (!preg_match("#[a-zA-Z]+#", $pwd)) {
      $errors[] = "Password must include at least one letter!";
   }     

   return ($errors == $errors_init);
}

source: https://stackoverflow.com/a/10753064/1676962

Community
  • 1
  • 1
2

You could use this regex :

preg_match('/(^(?=.*\d)(?=.*[a-z]).{8,}$)/i', $password);

Details :

  • (?=.*\d) : at least one digit
  • (?=.*[a-z]) : at least one letter
  • .{8,} : 8 or more characters
  • /i : case insensitive regex

Regular expression visualization

zessx
  • 68,042
  • 28
  • 135
  • 158
0

this is the regex :

^((?=.*\w)|(?=.*\d])).{8,}$

demo here : http://regex101.com/r/iU4mH1

aelor
  • 10,892
  • 3
  • 32
  • 48