Christian F. Posted March 7, 2013 Share Posted March 7, 2013 Continuing my posting of security-related functions in this section, I've decided to post this one up. I've posted a basic version of the RegExp previously, to which Psycho gave me some good feedback. Thus, the current function was born: // Define the flags used for validating passwords. define ('SF_VALIDATE_PASS_LOWER', 1); define ('SF_VALIDATE_PASS_UPPER', 2); define ('SF_VALIDATE_PASS_NUMERICAL', 4); define ('SF_VALIDATE_PASS_SPECIAL', ; define ('SF_VALIDATE_PASS_ALL', 15); /** * Validates the password according to the flags and mininum length given. * * Returns true if the password matches the constraints, or false if it fails. * * Default minimum length is 8 characters, and all flags activated. * * @author Christian Fagerheim (Fagerheim Software) * @link www.fagsoft.no * @license Creative Commons Attribution-ShareAlike 3.0. http://creativecommons.org/licenses/by-sa/3.0/. * * @param string $password * @param int[optional] $minLength * @param int[optional] $flags * * @return bool */ function validatePassword ($password, $minLength = 8, $flags = SF_VALIDATE_PASS_ALL) { // Make sure we got a valid minimum length. if (!is_int ($minLength) || $minLength < 0) { trigger_error ('Minimum length must be a positive integer', E_USER_ERROR); } // Create the constraints for the password. $passReg = ''; if ($flags & SF_VALIDATE_PASS_LOWER) { $passReg .= '(?=.*[a-z])'; } if ($flags & SF_VALIDATE_PASS_UPPER) { $passReg .= '(?=.*[A-Z])'; } if ($flags & SF_VALIDATE_PASS_NUMERICAL) { $passReg .= '(?=.*\\d)'; } if (false && $flags & SF_VALIDATE_PASS_SPECIAL) { $special = preg_quote (',.;:"\'!?*(){}[]/^§|#¤%&_=<>@£$€ +-', '/'); $passReg .= "(?=.*[$special])"; } // Add the minimum length requirement. $passReg .= '.{'.$minLength.',}'; // Check that the password matches the constraints, and return a boolean. if (!preg_match ("/^$passReg\\z/u", $password)) { return false; } return $password; } Link to comment https://forums.phpfreaks.com/topic/275364-function-to-validate-password-length-and-complexity/ Share on other sites More sharing options...
Christian F. Posted March 7, 2013 Author Share Posted March 7, 2013 Just noticed a little mistake in the code above. For some reason there's an extra false && which shouldn't be there, in the final constraint check. Remove it to make the special characters limitation apply. Link to comment https://forums.phpfreaks.com/topic/275364-function-to-validate-password-length-and-complexity/#findComment-1417217 Share on other sites More sharing options...
Recommended Posts