Search code examples
phpvalidationrespect-validation

Respect validation find messages for specific key


How can I get a custom message for a specific key of my validation?

For example this:

try {
    Respect\Validation\Validator::create()
        ->key('foo', v::length(20))
        ->key('bar', v::max(5))
        ->assert([
            'foo' => 'Hello, world!',
            'bar' => 30,
        ]);
} catch (Respect\Validation\Exceptions\ValidationException $exception) {
    $errors = $exception->findMessages([
        'key' => 'My custom message',
    ]);
    var_dump($errors, $exception->getFullMessage());
}

Returns this:

array (size=1)
  'key' => string 'My custom message' (length=17)

\-These rules must pass for "Array"
  |-My custom message
  | \-These rules must pass for "Hello, world!"
  |   \-"Hello, world!" must have a length greater than 20
  \-Key bar must be valid on bar
    \-These rules must pass for "30"
      \-"30" must be lower than 5

How can I make a custom message for the foo key, and separately the bar key?


Solution

  • Try this:

    try {
        Respect\Validation\Validator::create()
            ->key('foo', v::length(20))
            ->key('bar', v::max(5))
            ->assert([
                'foo' => 'Hello, world!',
                'bar' => 30,
            ]);
    } catch (Respect\Validation\Exceptions\ValidationException $exception) {
        $errors = $exception->findMessages([
            'foo' => 'My foo message',
            'bar' => 'My bar message',
        ]);
        var_dump($errors, $exception->getFullMessage());
    }
    

    Also note this should work with nested arrays:

    try {
        Respect\Validation\Validator::create()
            ->key('foo', v::length(20))
            ->key('bar', v::arr()
                ->key('baz', v::max(5))
            )
            ->assert([
                'foo' => 'Hello, world!',
                'bar' => [
                    'baz' => 30,
                ]
            ]);
    } catch (Respect\Validation\Exceptions\ValidationException $exception) {
        $errors = $exception->findMessages([
            'foo' => 'My custom foo message',
            'bar' => 'My custom bar message',
            'baz' => 'My custom baz message',
        ]);
        var_dump($errors, $exception->getFullMessage());
    }