Enforcing Password Requirements

丶灬走出姿态 提交于 2019-12-20 10:36:27

问题


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)


来源:https://stackoverflow.com/questions/6182846/enforcing-password-requirements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!