Simple password validator for PHP using mb_ereg_match

Password validation (in any programming language) can be a PITA. In case you happen to work with PHP and want to use a multi-byte compatible function, here’s something for you 🙂

It’s probably not foolproof, and you can probably find ways to improve upon it. Feel free to do so. If you break it, you own all the pieces.

 

 

/*
 * Simple password construct validator for PHP
 * This code uses mb_ereg_match()
 * Joaquim Homrighausen <joho@webbplatsen.se>
 * Mar 19, 2024
 *
 * Do whatever you want with this snippet :)
 *
 * This may not necessarily agree with the section "Strength of Memorized
 * Secrets" in the document from NIST:
 *
 * NIST Special Publication 800-63B
 * Digital Identity Guidelines
 * Authentication and Lifecycle Management
 * https://pages.nist.gov/800-63-3/sp800-63b.html
 */


/*
 * Requires that password is at least $min_length characters long (default 8).
 * Requires that password contains at least one UPPERCASE character.
 * Requires that password contains at least one lowercase character.
 * Requires that password contains at least one digit.
 * Requires that password contains at least one of the following:
 *   ^ ! @ # $ % & * _ - \ / { } [ ] .
 */

function password_mb_ereg_test( $password_string, $min_length = 8 ) {
    if ( $min_length < 8 ) {
        // We want at least eight characters, but probably 64 ;-)
        $min_length = 8;
    }                                   
    $match_rules = '^(?=.+[\.\^\!\@\#\$\%\^\&\*\-\_\\\/\[\]\{\}])(?=.+[[:digit:]])(?=.+[[:upper:]])(?=.+[[:lower:]]).{' . (int)$min_length . ',}$';
    return ( mb_ereg_match( $match_rules, $password_string ) );
}

This is also available as a gist on GitHub. Knock yourself out 🙂

There’s a similar variant using preg_match() available here:
Simple password validator for PHP

Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.

This site uses Akismet to reduce spam. Learn how your comment data is processed.