大家好,感谢您的帮助。 我想自定义错误消息以验证和 最终为每种语言创建不同的版本,可能吗?
这里我的代码处于实际状态。
namespace App;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Exceptions\NestedValidationException;
use Respect\Validation\Validator as v;
class Validator {
private $messages = [
'lastname',
'firstname',
'phone',
'email',
'message'
];
//other functions and declarations of my class.
private function validationData() {
$rule = null;
switch ($this->page) {
case 'contact';
$rule = v::key('lastname', v::notEmpty()
->alpha("-'"))
->key('firstname', v::optional(v::alpha("-'")))
->key('phone', v::optional(v::phone()))
->key('email', v::email())
->key('message', v::optional(v::length(5, 500)));
break;
default;
break;
}
try {
$rule->assert($this->data);
} catch (ValidationException $exception) {
var_dump($exception->findMessages($this->messages));
}
}
}
它告诉我:
array(5) {
["lastname"]=> string(51) "lastname must contain only letters (a-z) and ""-'"""
["firstname"]=> string(0) ""
["phone"]=> string(38) "phone must be a valid telephone number"
["email"]=> string(25) "email must be valid email"
["message"]=> string(44) "message must have a length between 5 and 500"
}
我需要保留此验证结果的结构。因为我需要字段的名称才能在客户端显示它们。
再次感谢,
答案 0 :(得分:3)
您可以使用尊重/验证。
我想要自定义错误消息进行验证
定义消息时,只需使用表示错误的键和将显示的消息的值使其成为关联数组:
private $messages = [
'lastname' => 'Error for lastname',
'firstname' => 'Custom error for firstname',
'phone' => 'Custom error for phone',
'email' => 'Custom error for email',
'message' => 'Custom error for message'
];
并最终为每种语言创建不同的版本
您可以创建一个自定义函数,用于转换您想要的任何语言的消息:
$translateMessage = function($message){
$language = 'it'; //Retrieve your language here or use 'en' if you want your custom messages
$messages = [
'Key {{name}} must be present' => [
'en' => 'Key {{name}} SHOULD be present',
'it' => 'La chiave {{name}} deve essere presente'
],
'{{name}} must be a string' => [
'en' => '{{name}} SHOULD be a magic custom string',
'it' => '{{name}} deve essere una stringa'
],
'{{name}} must contain only letters (a-z)' => [
'en' => '{{name}} SHOULD contain only my letters (a-z)',
'it' => '{{name}} deve contenere solo lettere (a-z)'
],
'{{name}} must contain only letters (a-z) and "{{additionalChars}}"' => [
'en' => '{{name}} must contain only letters (a-z) and "{{additionalChars}}',
'it' => '{{name}} deve contenere solo lettere (a-z) e "{{additionalChars}}"'
]
];
return $messages[$message][$language];
};
然后在 catch 块中使用它:
catch (ValidationException $exception) {
$exception->setParam('translator', $translateMessage);
var_dump($exception->findMessages($this->messages));
}