Advertisement
reenadak

validate password

Feb 20th, 2018
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.71 KB | None | 0 0
  1.    
  2.     /*
  3.     - Password validator
  4.     - Ensures a password entered on registration meets specific requirements.
  5.     - If it returns 0 that means it passed
  6.     - If it returns 1 that means the password has less than the minimum characters
  7.     - If it returns 2 that means the password contains less than the minimum special characters
  8.     - If it returns 3 that means the password contains less than the minimum numbers
  9.     - If it returns 4 that means the password contains less than the minimum capital letters
  10.    
  11.     $password               - The password to validate
  12.     $minChars               - The minimum amount of characters the password is permitted to have
  13.     $leastSpecialCharacters - The minimum amount of special characters permitted
  14.     $leastNumbers           - The minimum amount of numbers permitted
  15.     $leastCapitalLetters    - The minimum amount of capital letters permitted
  16.     */
  17.    
  18.     public function validatePassword($password, $minChars = 6, $leastSpecialCharacters = 0, $leastNumbers = 0, $leastCapitalLetters = 0) {
  19.         $valid = 0;
  20.        
  21.         if (strlen($password) < $minChars)
  22.             $valid = 1;
  23.        
  24.         $numSpecialChars = 0;
  25.         $numNumbers = 0;
  26.         $numCapitalLetters = 0;
  27.        
  28.         // iterate through each character in password
  29.         for ($i = 0; $i < strlen($password); $i++) {
  30.             $char = substr($password, $i, 1);
  31.            
  32.             if (!preg_match("#^[a-zA-Z0-9]+$#", $char))
  33.                 $numSpecialChars++;
  34.             elseif (preg_match("#^[A-Z]+$#", $char))
  35.                 $numCapitalLetters++;
  36.             elseif (preg_match("#^[0-9]+$#", $char))
  37.                 $numNumbers++;
  38.         }
  39.        
  40.         if ($numSpecialChars < $leastSpecialCharacters)
  41.             $valid = 2;
  42.        
  43.         if ($numNumbers < $leastNumbers)
  44.             $valid = 3;
  45.        
  46.         if ($numCapitalLetters < $leastCapitalLetters)
  47.             $valid = 4;
  48.        
  49.         return $valid;
  50.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement