PHP code example of franzose / kontrolio

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

    

franzose / kontrolio example snippets


// In container unaware environments
$valid = Factory::getInstance()->make($data, $rules, $messages)->validate();

// Using a service container implementation
$container->singleton('validation', static fn() => new Factory());
$container->get('validation')->make($data, $rules, $messages)->validate();

$validator = new Validator($data, $rules, $messages)->extend($custom)->validate();

$data = [
    'foo' => 'bar',
    'bar' => 'baz',
    'baz' => 'taz'
];

$rules = [
    'one' => 'not_empty|length:5,15',
    'two' => new Email,
    'three' => static fn ($value) => $value === 'taz',
    'four' => [
        static fn ($value) => is_numeric($value),
        new GreaterThan(5),
    ]
];

'some' => [
    new NotEmpty,
    new Length(5, 15)
]

'some' => [
    MyRule::allowingEmptyValue(),
    // (new MyRule())->allowEmptyValue()
]


class MyRule extends AbstractRule
{
    public function canSkipValidation($input = null)
    {
        return $input === 'bar';
    }

    // ...
}


    'foo' => static fn ($value) => is_string($value),
    'bar' => static function ($value) {
        return [
            // r
            'empty_allowed' => true, // allowing empty value
            'skip' => false // don't allow skipping current rule validation,
            'violations' => [] // rule violations
        ];
    }

$factory = (new Factory())->extend([CustomRule::class]);

// with a custom identifier
$factory = (new Factory())->extend(['some_custom' => CustomRule::class]);
$validator = $factory->make([], [], []);

// if you don't use factory
$validator = new Validator([], [], []);
$validator->extend([CustomRule::class]);

// with a custom identifier
$validator->extend(['custom' => CustomRule::class]);
$validator->validate();

$rules = [
    'one' => 'sometimes|length:5,15',
    // 'one' => [
    //     new Sometimes(),
    //     new Length(5, 15)
    // ]
];

$validator->shouldStopOnFailure()->validate();

$data = [
    'attr' => '',
    'attr2' => 'value2'
];

$rules = [
    'attr' => [
        new UntilFirstFailure(),
        new NotBlank(),
        new NotFooBar()
    ]
];

$messages = [<...>];

$validator = new Validator($data, $rules, $messages)->validate();

$messages = [
    'foo' => 'Foo cannot be null',
    'foo.length' => 'Wrong length of foo',
    'foo.length.min' => 'Foo is less than 3'
    // '[attribute].[rule].[violation]
];