3

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?

Petah
  • 45,477
  • 28
  • 157
  • 213

1 Answers1

5

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());
}
Petah
  • 45,477
  • 28
  • 157
  • 213
alganet
  • 2,527
  • 13
  • 24
  • In 2018, the `->findMessages()` method is not on the base `ValidationException` class as listed in the excerpt above, but is actually part of `Respect\Validation\Exceptions\NestedValidationException`. If you fail to use the latter type in your `catch` block, PHP7 will throw. – BHarms May 17 '18 at 13:57