PHP code example of krak / validation

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

    

krak / validation example snippets




$validation = new Krak\Validation\Kernel();
$validator = $validation->make([
    'name' => ' => 'RJ',
    'age' => 17,
]);

if ($violations) { // you can also check $validator->failed()
    print_r($violations->format()); // format into an array of error messages
}



use Krak\Validation;

/** enforces that a value equals a specific value */
function equalsStringValidator($match) {
    return function($value, array $ctx = []) use ($match) {
        if ($value == $match) {
            return;
        }

        return Validation\violate('equals_string', [
            'match' => $match
        ]);
    };
}

$v = equalsStringValidator('foo');
$v('foo'); // returns null
$violation = $v('bar'); // return a Krak\Validation\Violation



try {
    $violation->abort();
} catch (Krak\Validation\Exception\ViolationException $e) {
    assert($e->violation === $violation);
}

$validation = new Krak\Validation\Kernel();
$validation->make([
    'name' => 'e' => 100]);
// this will have thrown a ViolationException due to the age constraint

try {
    return response($storeUser($userData), 201);
} catch (Krak\Validation\Exception\ViolationException $e) {
    return response([
        'errors' => $e->violation->format(),
    ], 422);
}

interface ValidationPackage
{
    public function withValidation(Kernel $validation);
}



use Krak\Validation;

class AcmeValidationPackage implements Validation\ValidationPackage
{
    public function withValidation(Validation\Kernel $v) {
        $v->validators([
            'integer' => 'intValidator', // name of intValidator func
            'min' => MinValidator::class // name of MinValidator class
        ]);
        $v->messages([
            'integer' => 'The {{attribute}} is not a valid integer',
            'min' => 'The {{attribute}} size must be greater than or equal to {{min}}',
        ]);
        $v->aliases([
            'int' => 'integer',
        ]);
    }
}

use Krak\Validation;

// intValidator.php
function intValidator() {
    return function($v) {
        return !is_int($v) ? Validation\violate('integer') : null;
    };
}

// MinValidator.php
class MinValidator implements Validation\Validator
{
    private $min;

    public function __construct($min) {
        $this->min = $min;
    }

    public function validate($value, array $context = []) {
        return $value < $min ? Validation\violate('min', ['min' => $this->min]) : null;
    }
}

$validator->make('all:integer')->validate([1,2,3]);

use function Krak\Validation\Validators\{forAll};
$validator->make(forAll('integer|between:1,3'))->validate([1,2,3])

use function Krak\Validation\Validators\{forAll, typeInteger};

forAll(typeInteger())([2,3]);

$validator->make('alpha')->validate('abc');

use function Krak\Validation\Validators\{alpha};

alpha()('123');

$validator->make('alpah_num')->validate('abc123');

use function Krak\Validation\Validators\{alphaNum};
alphaNum()('abc123');

$validator->make('array')->validate();

use function Krak\Validation\Validators\{typeArray};

typeArray()([]);

$validator->make('between:1,2')->validate(2);

use function Krak\Validation\Validators\{between};

between(1, 2)(2);

$validator->make('boolean')->validate(true);

use function Krak\Validation\Validators\{typeBoolean};

typeBoolean()(true);

$validator->make('date')->validate('2017-08-11');

use function Krak\Validation\Validators\{date};

date()('2017-08-11');

$validator->make('digits')->validate('123');

use function Krak\Validation\Validators\{digits};

digits()('123');

$validator->make('double')->validate(4.2);

use function Krak\Validation\Validators\{double};

double()(4.2);

$validator->make('email')->validate('[email protected]');

use function Krak\Validation\Validators\{regexEmail};

regexEmail()('[email protected]');

$validator->make('float')->validate(4.2);

use function Krak\Validation\Validators\{float};

float()(4.2);

$validator->make('in:a,b,c')->validate('b');

use function Krak\Validation\Validators\{inArray};

inArray(['a', 'b', 'c'])('b');

$validator->make('integer')->validate(1);

use function Krak\Validation\Validators\{typeInteger};

typeInteger()(1);

$validator->make('length:3')->validate('abc');

use function Krak\Validation\Validators\{length};

length()('abc');

$validator->make('max:5')->validate(4);

use function Krak\Validation\Validators\{max};

max(5)(4);

$validator->make('min:2')->validate(3);

use function Krak\Validation\Validators\{min};

min(2)(3);

$validator->make('null')->validate(null);

use function Krak\Validation\Validators\{typeNull};

typeNull()(null);

$v = $validator->make('nullable|integer');
$v->validate(null);
$v->validate(1);

use function Krak\Validation\Validators\{pipe, nullable, typeInteger};

$v = pipe([nullable(), typeInteger()]);
$v(null);
$v(1);

$validator->make('number')->validate(1);

use function Krak\Validation\Validators\{number};

number()(1);

$validator->make('numeric')->validate('1.5');

use function Krak\Validation\Validators\{typeNumeric};

typeNumeric()('1.5');

$v = $validator->make([
    'id' => 'optional|integer'
]);
$v->validate([]);
$v->validate(['id' => 1])

use function Krak\Validation\Validators\{collection, optional, typeInteger, pipe};

$v = collection([
    'id' => pipe([optional(), typeInteger()])
]);
$v([]);
$v(['id' => 1]);

$validator->make('regex:/a+b/')->validate('aaab');

use function Krak\Validation\Validators\{regexMatch};

$validator->make(regexMatch('/(aa|bb)/'))->validate('aa');

use function Krak\Validation\Validators\{regexMatch};

regexMatch('/(aa|bb)/')('aa');

$validator->make('regex:/a+b/')->validate('c');

use function Krak\Validation\Validators\{regexExclude};

$validator->make(regexExclude('/(aa|bb)/'))->validate('cc');

use function Krak\Validation\Validators\{regexExclude};

regexExclude('/(aa|bb)/')('cc');

$validator->make([
    'id' => '

use function Krak\Validation\Validators\{collection, pipe, typeInteger,  1]);

$validator->make('string')->validate('a');

use function Krak\Validation\Validators\{typeString};

typeString()('a');

$validation = new Krak\Validation\Kernel();
$validation->withDoctrineValidators();
// only needed for doctrine_entities, doctrine_entity, and doctrine_unique_entity
$validation['Doctrine\Common\Persistence\ObjectManager'] = function() {
    // return a configured entity manager here...
};
$validation['Doctrine\DBAL\Connection'] = function() {
    // return a dbal connection here
};
$validation->context([
    'doctrine.model_prefix' => Acme\Model::class,
]);

$validator->make('array|all:integer|doctrine_all_exist:users')->validate([1,2,3]);

use Krak\Validation\Validators\Doctrine\AllExist;
use function Krak\Validation\Validators\{pipe, typeInteger, forAll};

pipe([forAll(typeInteger), new AllExist('users')])([1,2,3]);

$validator->make('array|all:integer|doctrine_entities:User')->validate([1,2,3]);

use Krak\Validation\Validators\Doctrine\Entities;
use function Krak\Validation\Validators\{pipe, typeInteger, forAll};

pipe([forAll(typeInteger), new Entities('User')])([1,2,3]);

$validator->make('doctrine_entity:User')->validate(1);

use Krak\Validation\Validators\Doctrine\Entity;

(new Entity('User'))->validate(1);

$validator->make('doctrine_entity:users')->validate(5);

use Krak\Validation\Validators\Doctrine\Exists;

(new Exists('users'))->validate(5);

$validator->make('doctrine_unique:users,email')->validate('[email protected]');

use Krak\Validation\Validators\Doctrine\Unique;

(new Unique('users', 'email'))->validate('[email protected]');

$validator->make('doctrine_unique_entity:User,email')->validate('[email protected]');

use Krak\Validation\Validators\Doctrine\UniqueEntity;

(new UniqueEntity('User', 'email'))->validate('[email protected]');

function($value, array $ctx = [])