【问题标题】:Laravel add error message to validator in custom form requestLaravel 在自定义表单请求中向验证器添加错误消息
【发布时间】:2020-06-02 06:38:53
【问题描述】:

我有一个自定义表单请求,我在其中执行了一些额外的验证逻辑,如果我的逻辑失败但我收到此错误,我想添加一个错误:

在 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',
        ];
    }
}

【问题讨论】:

  • 在 null 上调用成员函数 errors() 意味着 $this->validator 为 null。请检查你在哪里初始化了 $this->validator
  • @Sehdev 它来自扩展我的自定义表单请求的 FormRequest laravel.com/docs/5.8/validation#creating-form-requests
  • 你能把全班的代码灌进去吗?
  • @V-K 查看完整代码编辑

标签: php laravel


【解决方案1】:

我认为您需要按照 laravel doc 的建议添加钩子 withValidator。

public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}

【讨论】:

  • 我在哪里调用这个 withValidator() 函数呢?
  • @user3652775 在表单请求文件中。
  • 这对我来说没有意义我很抱歉
  • @user3652775 请阅读此文档以了解更多信息:laravel.com/docs/5.8/validation#form-request-validation
  • 我没有看到或读到我需要调用这个函数的地方: withValidator($validator) 它只是说我可以做到。好的,我把它放在我的 ProfileRequest 中,但它从来没有被调用过?
猜你喜欢
  • 2012-05-07
  • 2017-05-30
  • 2014-04-05
  • 2019-11-27
  • 2017-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-30
相关资源
最近更新 更多