我在laravel中遇到自定义验证消息的问题。 我要验证用户创建请求,我的数据如下:
first_name:Akhsay middle_name:R last_name:Doe gender:male miscellaneous:{"dob":"","birth_name":"xyz"}
我已经创建了用于在userCreateRequest.php中创建用户的验证规则
public function rules()
{
return [
'first_name' => 'required',
'middle_name' => 'required',
'last_name' => 'required',
'gender' => 'required',
'miscellaneous' => 'json|validate_misc_info',
];
}
/**
* validation messages
*
* @return array
*/
public function messages()
{
return [
"first_name.required" => "First name is required.",
"middle_name.required" => "Middle name is required.",
"last_name.required" => "Last name is required.",
"gender.required" => "Gender is required.",
'miscellaneous.validate_misc_info' => '(**want to show specific error message here**)?'
];
}
对于其他信息,我创建了一个自定义验证服务提供程序,并且在自定义验证器的启动方法中,我将验证代码编写为
Validator::extend('validate_misc_info',function($attribute, $value, $params, $validator) {
$data = json_decode($value, true);
$rules = [
"dob" => "required|date",
"birth_name" => "required|min:2|max:50",
];
$messages= [
"dob.required" => "Date of birth is required",
"birth_name.required" => "Birth name is required",
];
$validator = $data ? Validator::make($data, $rules, $messages) : false;
if ($validator && $validator->fails()) {
return false;
}
return true;
});
但是当我在userCreateRequest.php中使用此验证规则时
public function rules()
{
return [
'first_name' => 'required',
'middle_name' => 'required',
'last_name' => 'required',
'initial' => 'required',
**'miscellaneous' => 'json|validate_misc_info',**
];
}
它向我显示错误
{
"message": "The given data was invalid.",
"errors": {
"miscellaneous": [
"validation.validate_misc_info"
]
}
但我想显示特定的错误消息为
{
"message": "The given data was invalid.",
"errors": {
"miscellaneous": [
"Date of birth is required"
]
}
请帮助我。