Skip to content

Latest commit

 

History

History
executable file
·
91 lines (62 loc) · 2.54 KB

15.2 - After validation event.md

File metadata and controls

executable file
·
91 lines (62 loc) · 2.54 KB

15.2 - After event

The after event will be triggered after validation is complete. Here you can check the validated data, if validation passed or not, retrieve the error bag and more. This can be handy if you want to log all failed validation to a database i.e.

Like with the before event, you can use a closure function or an object class as event handler.

Using a closure function:

use KrisKuiper\Validator\Blueprint\Events\AfterEvent;
use KrisKuiper\Validator\Validator;

$data = ['email' => 'email@domain.com'];
$validator = new Validator($data);

//Attach a new before event listener
$validator->after(function (AfterEvent $event) {

    //Check if validation failed
    if($event->failed()) {
        
        //Log all the validated data and errors into the database
        $DB->logFailedValidation(
            $event->getValidatedData()->toArray(), 
            $event->errors()
        );
    }
});

//Attach validation rules
$validator->field('email')->required()->email();

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

Using a class object:

Create a new class CustomAfterHandler that implements the AfterEventInterface:

use KrisKuiper\Validator\Blueprint\Contracts\AfterEventInterface;
use KrisKuiper\Validator\Blueprint\Events\AfterEvent;

final class CustomAfterEventHandler implements AfterEventInterface
{
    public function handle(AfterEvent $event): void
    {
        //Check if validation failed
        if($event->failed()) {

            //Log all the validated data and errors into the database
            $DB->logFailedValidation(
                $event->getValidatedData()->toArray(), 
                $event->errors()
            );
        }
    }
}

Use this class in the validation:

use KrisKuiper\Validator\Blueprint\Events\AfterEvent;
use KrisKuiper\Validator\Validator;

$data = ['email' => 'email@domain.com'];
$validator = new Validator($data);

//Attach the after event listener
$validator->loadAfterEvent(new CustomAfterEventHandler());

//Attach validation rules
$validator->field('email')->required()->email();

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

Note: The after event is also attachable to blueprint validators.


Go to the previous section.

Go to the next section.