[英]Laravel add error message to validator in custom form request
我有一个自定义表单请求,我在其中执行一些额外的验证逻辑,如果我的逻辑失败,我想添加一个错误,但出现此错误:
在 null 上调用成员函数 errors()
这是我的自定义请求:
if (!empty($this->get('new_password')) && !empty($this->get('current_password'))) {
if (
!Auth::attempt([
'email' => $this->get('email'),
'password' => $this->get('current_password'),
'status' => 'pending'
])
) {
$this->validator->errors()->add('current_password', 'Something is wrong with this field!');
}
}
return [
'first_name' => 'required|min:1|max:190',
];
class ProfileRequest extends FormRequest
{
public function authorize()
{
return Auth::check();
}
public function rules()
{
if (!empty($this->get('new_password')) && !empty($this->get('current_password'))) {
if (
!Auth::attempt([
'email' => $this->get('email'),
'password' => $this->get('current_password'),
'status' => 'pending'
])
) {
$this->validator->getMessageBag()->add('current_password', 'Something is wrong with this field!');
}
}
return [
'first_name' => 'required|min:1|max:190',
];
}
}
我认为您需要按照 laravel 文档的建议添加withValidator
钩子。
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add('field', 'Something is wrong with this field!');
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.