PHP code example of kanellov / password-strength-validator

1. Go to this page and download the library: Download kanellov/password-strength-validator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kanellov / password-strength-validator example snippets




// force password to contain at least one digit and one uppercase char
$flags = KNLV_PWD_CONTAIN_DGT | KNLV_PWD_CONTAIN_UC;
$password = "somePasswordNotContainingDigits";

$code = 0;
$message = '';
$is_valid = true;
try {
    \Knlv\password_strength($password, $flags);
} catch(\ErrorException $e) {
    $is_valid = false;
    $code = $e->getCode();
    $message =  $e->getMessage();
}

var_dump($is_valid, $code, $message);
/* --- RESULTS ---
 * bool(false)
 * int(1)
 * string(50) "Password must contain at least one digit character"
 */



use \Knlv\Validator\PasswordStrength;

$password = "somePasswordNotContainingDigits";
$validator = new PasswordStrength(array('flags' => KNLV_PWD_CONTAIN_DGT | KNLV_PWD_CONTAIN_UC));
$is_valid = $validator->isValid($password);
$messages = $validator->getMessages();

var_dump($is_valid, $messages);

/* --- RESULTS ---
 * bool(false)
 * array(1) {
 *   [1]=>
 *   string(50) "Password must contain at least one digit character"
 * }
 */
 

// force password to contain at least one symbol char
$flags = KNLV_PWD_CONTAIN_SYM;
$password = "p@ssword!";
$exclude = "@!"; // exclude @ and ! symbols

$code = 0;
$message = '';
$is_valid = true;
try {
    \Knlv\password_strength($password, $flags, $exclude);
} catch(\ErrorException $e) {
    $is_valid = false;
    $code = $e->getCode();
    $message =  $e->getMessage();
}

var_dump($is_valid, $code, $message);
/* --- RESULTS ---
 * bool(false)
 * int(8)
 * string(51) "Password must contain at least one symbol character"
 */
 
 
 // Using validator
 
$password = "p@ssword!";
$validator = new \Knlv\Validator\PasswordStrength(array(
    'flags' => KNLV_PWD_CONTAIN_SYM,
    'excludedSymbols' => '@!',
));
$is_valid = $validator->isValid($password);
$messages = $validator->getMessages();

var_dump($is_valid, $messages);
/* --- RESULTS ---
 * bool(false)
 * array(1) {
 *   [8]=>
 *   string(51) "Password must contain at least one symbol character"
 * }
 */