PHP code example of crysalead / validator

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

    

crysalead / validator example snippets


$v = new Validator();

$v->rule('title', [
    'not:empty',
    'lengthBetween' => ['min' => 3, 'max' => 20]
]);

$v->validate(['title' => 'new title']); // boolean
$v->errors(); // errors ?

$v = new Validator();
$v->rule('emails.*', 'email');

$v->validate(['emails' => [
    '[email protected]', '[email protected]']
]);

$v = new Validator();
$v->rule('people.*.email', 'email');

$v->validate([
    'people' => [
        ['email' => '[email protected]'],
        ['email' => '[email protected]']
    ]
]);

$v = new Validator();
$v->set('zeroToNine', '/^[0-9]$/');

$v = new Validator();
$v->set('postalCode', [
    'us' => '/^\d{5}(?:[-\s]\d{4})?$/',
    'fr' => '/^(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$/',
    'uk' => '/^(GIR|[A-Z]\d[A-Z\d]??|[A-Z]{2}\d[A-Z\d]??)[ ]??(\d[A-Z]{2})$/'
]);

$v->message('postalCode', 'invalid postal code');

$v->rule('zip', 'postalCode');

$v->validate(['zip' => '30700'], ['check' => 'fr']);  // check only the fr validation handler.
$v->validate(['zip' => '30700'], ['check' => 'any']); // default behavior.

$v = new Validator();
$v->set('zeroToNine', function($value, $options = [], &$params = []) {
    return preg_match('/^[0-9]$/', $value);
});

$v = new Validator();
$v->set('zeroToNine', '/^[0-9]$/');

Validator::messages([
    'zeroToNine' => 'must be between 0 to 9'
]);

$v->rule('checksum', 'zeroToNine');
$v->validate(['checksum' => '25']);
$v->errors(); // returns ['zeroToNine' => ['must be between 0 to 9']]

Checker::set('zeroToNine', '/^[0-9]$/');
Checker::message('zeroToNine', 'must be between 0 to 9');

$v = new Validator();
$v->rule('checksum', 'zeroToNine');
$v->validate(['checksum' => '25']);
$v->errors(); // returns ['zeroToNine' => ['must be between 0 to 9']]

$v = new Validator();

$v->rule('title', [
    'not:empty' => [
        'message' => 'please enter a {:label}',
        'label' => 'title'
    ],
    'lengthBetween' => [
        'min' => 3,
        'max' => 20,
        'message' => 'must be between {:min} and {:max} character long'
    ]
]);

$v = new Validator([
    'error' => function($name, $options, $meta = []) {
        $message = __t($options['message'] ?: $name); // <- put here your logic to perform translations
        return Text::insert($message, $options);
    }
]);