Skip to content

Latest commit

 

History

History
executable file
·
70 lines (52 loc) · 1.44 KB

17.4 - Using blueprints.md

File metadata and controls

executable file
·
70 lines (52 loc) · 1.44 KB

17.4 - Using blueprints example

use KrisKuiper\Validator\Blueprint\Blueprint;
use KrisKuiper\Validator\Error;
use KrisKuiper\Validator\Validator;

$data = [
    'name' => 'Morris',
    'role' => 'moderator',
    'email' => '[email protected]',
    'password' => 'very_strong_password',
    'password_repeat' => 'very_strong_password',
];

//Create blueprint
$blueprint = new Blueprint();

$blueprint
    ->field('name')
    ->isString()
    ->lengthBetween(2, 30)
    ->required();

$blueprint
    ->field('role')
    ->in(['admin', 'moderator', 'user'])
    ->required();

$blueprint
    ->field('email')
    ->email()
    ->lengthBetween(5, 50);


//Use the blueprint in the validator
$validator = new Validator($data);

$validator
    ->loadBlueprint($blueprint);

$validator
    ->field('password')
    ->required()
    ->lengthBetween(8, 50);

$validator
    ->field('password_repeat')
    ->same('password');

//Validation passes
if($validator->passes()) {
    print_r($validator->validatedData()->not('password_repeat')->toArray());
}

//Validation fails
if($validator->fails()) {

    $validator->errors()->each(function(Error $error) {
        print_r($error->getMessage());
    });
}

Go to the previous section.

Go to the next section.