Jump to content


This topic is now archived and is closed to further replies.

Christian F.

Function to validate password length and complexity.

Recommended Posts

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_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])';
		$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;

Share this post

Link to post
Share on other sites

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.

Share this post

Link to post
Share on other sites


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.