Skip to content

Latest commit

 

History

History
executable file
·
85 lines (60 loc) · 2.68 KB

7.1 - Filtering values based on validation rules.md

File metadata and controls

executable file
·
85 lines (60 loc) · 2.68 KB

7.1 - Filtering values based on validation rules

Sometimes, you just want to retrieve the valid (or invalid) values from an array based on a set of validation rules. This can be done with the filter() method. This method is available in the validator, in the before event and in custom validation rules.

Example: in the validator

use KrisKuiper\Validator\Validator;

$data = ['months' => [1, 2, '3', 4, '6', '7', 8, 13]];

$validator = new Validator($data);
$validMonths = $validator
    ->filter('months.*')
    ->isInt(true)
    ->between(1, 12)
    ->toArray(); //[1, 2, 4, 8]

Example 2: in the before event

use KrisKuiper\Validator\Blueprint\Events\BeforeEvent;
use KrisKuiper\Validator\Validator;

$data = ['ids' => [1, 2, '3', 4, '6', '7', 8]];

$validator = new Validator($data);
$validator->before(function(BeforeEvent $event) {

    //Filter all the id's that matches the validation rules
    $ids = $event->filter('ids.*')->isInt(true)->between(0, 5)->toArray(); //[1, 2, 4]
    
    //Retrieve the products from the database based on the valid id's
    //and store the result in the validator storage
    $event->storage()->set('validIds', $database->getIds($ids));
});

$validator->field('ids.*')->in($validator->storage()->get('validIds'));

//Execute validation
$validator->passes();

Example 3: in a custom rule

use KrisKuiper\Validator\Blueprint\Events\Event;
use KrisKuiper\Validator\Validator;

$data = ['ids' => [1, 2, '3', 4, '6', '7', 8]];

$validator = new Validator($data);
$validator->custom('myRule', function(Event $event) {

    //Filter all the id's that matches the validation rules
    $ids = $event->filter('ids.*')->isInt(true)->between(0, 5)->toArray(); //[1, 2, 4]
    
    return count($ids) > 2;
});

$validator->field('ids.*')->custom('myRule');

//Execute validation
$validator->passes();

You can also retrieve all the invalid values by setting the filter mode:

use KrisKuiper\Validator\FieldFilter;
use KrisKuiper\Validator\Validator;

$data = ['months' => [1, 2, '3', 4, '6', '7', 8, 13]];

$validator = new Validator($data);
$inValidMonths = $validator
    ->filter('months.*', FieldFilter::FILTER_MODE_FAILED)
    ->isInt(true)
    ->between(1, 12)
    ->toArray(); //['3', '6', '7', 13]

Go to the previous section.

Go to the next section.