Respect / Validation

The most awesome validation engine ever created for PHP
https://respect-validation.readthedocs.io
MIT License
5.75k stars 774 forks source link

How to compare two field #1438

Closed ghabriel25 closed 7 months ago

ghabriel25 commented 7 months ago

I want to compare two field but with error message using field name for example

Start Year must be less than End Year

The error message that I get is

Start Year must be less than 2015 << End Year value

russelomua commented 7 months ago

Hello! You can use keyValue validator and add your Custom message on NestedValidationException handling.

$data = [
   'start_year' => 2020,
   'end_year' => 2019,
];

$validator = v::keyValue('start_year', 'greaterThan', 'end_year');

try {
    $validator->assert();
} catch (NestedValidationException $e) {
    $errors = $exception->getMessages([
        'start_year' => 'Start Year must be less than '. $data['end_year'],
    ]);

    echo json_encode($errors);
}