如何使用Laravel自定义消息验证器



我正在制作一个API,允许用户输入一些信息,如电子邮件,电话号码,地址…但是如果用户输入了错误的电话号码,则验证错误为

{
"message": "The given data was invalid.",
"errors": {
"phone": [
"The phone has already been taken."
]
}
}
如你所见,返回的消息是
"message": "The given data was invalid."

。但是我期望的信息是The phone has already been taken。我如何自定义我所期望的消息?对于电子邮件验证器,消息是相同的,但密钥是email。我期望的消息是

"message": "The ... has already been taken. "

我使用laravel 8并在请求中验证示例a函数rules()

public function rules()
{
return [
'profile_img' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:' . config('filesystems.max_upload_size'),
'name' => 'nullable|min:3',
'phone' => [
'required',
'numeric',
new UpdatePhoneRule(User::TYPE_CLIENT),
],
'email' => [
'nullable',
'email',
new UpdateEmailRule(User::TYPE_CLIENT),
]
];
}

感谢

在Request php文件中,您可以使用这个函数failedValidation()并传入一个Validator。这样,如果验证失败,您可以更改或自定义响应。

use IlluminateHttpExceptionsHttpResponseException;
use IlluminateContractsValidationValidator;
protected function failedValidation(Validator $validator) {
throw new HttpResponseException(response()->json(['status'=>'failed',
'message'=>'unprocessable entity',
'errors'=>$validator->errors()->all()], 422));
}

示例回答在这里…

{
"status": "failed",
"message": "unprocessable entity",
"errors": [
"The name must be a string.",
"One or more users is required"
]
}

正如你所看到的消息被改变了,现在你可以对响应消息做任何你想做的事情。

你也可以试试这个

$validator->errors()->messages()[keyname]

您必须在验证中使用unique

$this->validate(
$request, 
[   
'email'             => 'required|unique:your_model_names',
'phone'             => 'required|unique:your_model_names'
],
[   
'email.required'    => 'Please Provide Your Email Address For Better Communication, Thank You.',
'email.unique'      => 'Sorry, This Email Address Is Already Used By Another User. Please Try With Different One, Thank You.',
'phone.required' => 'Your custom message',
'phone.unique'      => 'The phone has already been taken'
]
);

您可以在lang文件:resources/lang/en/validation.php中完成此操作。如果你想做的只是改变,例如,在整个应用程序的电子邮件字段的唯一规则的消息,你可以这样做:

/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
'email' => [
'unique' => 'This email is already registered...etc',
]
],

相关内容

  • 没有找到相关文章

最新更新