如何获取我验证的特定密钥的自定义消息?
例如:
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());
}
返回:
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
如何为foo
密钥创建自定义消息,并单独创建bar
密钥?
答案 0 :(得分:4)
试试这个:
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());
}
另请注意,这应该适用于嵌套数组:
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());
}