PHP code example of dhii / validator

1. Go to this page and download the library: Download dhii/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/ */

    

dhii / validator example snippets


use Dhii\Validation\Exception\ValidationFailedExceptionInterface;use Dhii\Validator\CallbackValidator;
use Dhii\Validator\CompositeValidator;

$alphanum = new CallbackValidator(function ($value) {
    if (preg_match('![^\d\w]!', $value, $matches)) {
        return sprintf('Value "%1$s" must be alphanumeric, but contains char "%2$s"', $value, $matches[0][0]);
    }
});
$chars30 = new CallbackValidator(function ($value) {
    $length = strlen($value);
    if (!($length <= 30)) {
        return sprintf('Value "%1$s" is limited to 30 characters, but is %2$d characters long', $value, $length);
    }
});
$usernameValidator = new CompositeValidator([$alphanum, $chars30]);

// Valid username: nothing happens
$usernameValidator->validate('abcdef');

// Invalid username value: exception thrown
try {
    $percentValidator->validate('abcdefghijklmnopqrstuvwxyz!@#$%');
} catch (ValidationFailedExceptionInterface $e) {
    // Validation failed with 2 errors.
    echo $e->getMessage();
    // 1: Value "abcdefghijklmnopqrstuvwxyz!@#$%" must be alphanumeric, but contains char "!"
    // 2: Value "abcdefghijklmnopqrstuvwxyz!@#$%" is limited to 30 characters, but is 31 characters long
    foreach ($e->getValidationErrors() as $error) {
        echo (string) $error;
    }
}