Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PHP Password Validator

A standalone, dependency-free password validation helper for PHP 8.3+.

It validates passwords against configurable rules:

  • min / max length (minLength, maxLength)
  • complexity — required count of uppercase letters, lowercase letters, digits and special characters (minUppercase, minLowercase, minDigits, minSpecialChars)
  • custom format — an optional PCRE pattern the whole password must match (pattern)

Installation

composer require antoninom90/php-password-validator

Usage

use AntoninoM90\PasswordValidator\PasswordValidator;

$validator = new PasswordValidator(
    minLength: 8,
    maxLength: 72,
    minUppercase: 1,
    minLowercase: 1,
    minDigits: 1,
    minSpecialChars: 1,
    pattern: null,
);

$result = $validator->validate('Abcdef1!');

if ($result->isValid()) {
    // password accepted
} else {
    foreach ($result->getErrors() as $code => $message) {
        // $code: e.g. PasswordValidationResult::TOO_SHORT
    }
}

A convenience shortcut is also available:

if (!$validator->isValid($password)) {
    // ...
}

Options

Option Type Default Description
minLength int 8 Minimum number of characters.
maxLength ?int 72 Maximum number of characters; null disables the limit.
minUppercase int 0 Minimum number of uppercase letters.
minLowercase int 0 Minimum number of lowercase letters.
minDigits int 0 Minimum number of digits.
minSpecialChars int 0 Minimum number of special characters (anything that is not a letter, digit or whitespace).
pattern ?string null Optional full PCRE pattern the password must match, e.g. '/^[A-Za-z0-9._-]+$/'.

Invalid configuration (e.g. minLength < 1, maxLength < minLength, negative complexity or a malformed pattern) throws InvalidArgumentException at construction time.

Character classes and lengths are Unicode-aware, so multibyte passwords are handled correctly without requiring ext-mbstring.

Result codes

Code Meaning
TOO_SHORT Password shorter than minLength.
TOO_LONG Password longer than maxLength.
TOO_FEW_UPPERCASE Fewer uppercase letters than required.
TOO_FEW_LOWERCASE Fewer lowercase letters than required.
TOO_FEW_DIGITS Fewer digits than required.
TOO_FEW_SPECIAL_CHARS Fewer special characters than required.
INVALID_FORMAT Password does not match the pattern.

PasswordValidationResult::isValid() returns true when no violation was found. getCodes(), getMessages() and getErrors() expose the violations.

Tests

composer install
composer test

License

MIT — see LICENSE.

About

A standalone, dependency-free password validation helper for PHP 8.3+.

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages