Enforcing Password Requirements

2019-03-12 19:08发布

问题:

I want to check if the user has successfully met the following requirements:

  • The password has at least 8 characters
  • Consists of one capital & one lowercase letter

How would I do this?

I am using the PHP script below:

if ( strlen( $password ) < 8 ) {
     false
} else {
   if ( preg_match( "/[^0,9]/", $password ) ) {
     // how to check the upper case and lower case
   }
}

回答1:

You can do that with a regex:

if (!preg_match('/^(?=[a-z])(?=[A-Z])[a-zA-Z]{8,}$/', $password))
{
    //error
}


回答2:

Use preg_match("/[A-Z]/") and preg_match("/[a-z]/")



回答3:

if( strlen($password) < 8 ) {
     return false;
}
if(preg_match("/[^0,9]/", $password)) {
     how to check the upper case and lower case
}
if($password == strtoupper($password) || $password == strtolower($password)){
//pass fails because its either all upcase, or lowercase
}


回答4:

You may use a password ranking technique:

$x = "a12ASD!@#$";
$rank = Array();


$rank['length'] = strlen($x);

$matches = Array();
preg_match_all("/([a-z]+)/", $x, $matches);
$rank['lowercase'] = strlen(implode('', $matches[0]))/count($matches[0]);

$matches = Array();
preg_match_all("/([A-Z]+)/", $x, $matches);
$rank['uppercase'] = strlen(implode('', $matches[0]))/count($matches[0]);

$matches = Array();
preg_match_all("/([0-9]+)/", $x, $matches);
$rank['numbers'] = strlen(implode('', $matches[0]))/count($matches[0]);

$matches = Array();
preg_match_all("/([^a-zA-Z0-9]+)/", $x, $matches);
$rank['symbols'] = strlen(implode('', $matches[0]))/count($matches[0]);


echo "<pre>";
var_dump($rank);
echo "</pre>";


回答5:

if (
  strlen($password) >= 8) &&
  preg_match('/[A-Z]/', $password) > 0 &&
  preg_match('/[a-z]/', $password) > 0 )
{
  /* Password validation passes, do stuff. */
}
else {
  /* Password validation fails, show error. */
}


回答6:

You can use trim, which is actually much faster than regexp

if ( trim( $password, 'a..z') != '' && trim( $password, 'A..Z') != '' && strlen($password) >= 8 )
{
  /* Password validation passes, do stuff. */
}
else {
  /* Password validation fails, show error. */
}


回答7:

preg_match('/[a-z]/', $password) && preg_match('/[A-A]/', $password)