Skip to content

Latest commit

 

History

History
executable file
·
66 lines (47 loc) · 1.84 KB

13.3 - Custom middleware.md

File metadata and controls

executable file
·
66 lines (47 loc) · 1.84 KB

13.3 - Custom middleware

You can also define your own custom middleware.

Below is a blueprint/example of middleware which will prepend a zero if the value under validation is below 10 and higher than 0. This can be handy for dates i.e. validation of a month or day.

use KrisKuiper\Validator\Blueprint\Contracts\MiddlewareFieldInterface;
use KrisKuiper\Validator\Blueprint\Middleware\Transforms\AbstractMiddleware;

class LeadingZeroMiddleware extends AbstractMiddleware
{
    public function handle(MiddlewareFieldInterface $field): void
    {
        $value = $field->getValue();

        if (is_numeric($value) === false) {
            return;
        }

        $value = (float) $value;

        if ($value < 10 && $value >= 0) {
            //Set the new value for the validation rules to work with
            $field->setValue('0' . $value);
        }
    }
}

Once the middleware has been defined, you may attach it to a validator by passing the namespace of the middleware object:

use KrisKuiper\Validator\Validator;

$data = [
    'month' => 3
];

$validator = new Validator($data);

//Attach the custom middleware to the "month" field
$validator
    ->middleware('month')
    ->load(new LeadingZeroMiddleware());

//Attach the rules
$validator
    ->field('month')
    ->equals('03');

if($validator->passes()) {
    //Validation passes
}

//This will return ['month' => '03'] (mind the leading zero)
$validator->validatedData()->toArray();

Note: Middleware is also attachable to blueprint validators.


Go to the previous section.

Go to the next section.