【问题标题】:Laravel custom validation and ajaxLaravel 自定义验证和 ajax
【发布时间】:2018-05-31 20:10:09
【问题描述】:

我的 Laravel 4.2 项目的验证是使用 Ardent 包完成的。在使用 Laravel 5.5 之后,我已经淘汰了 Ardent,并希望通过表单请求进行 Laravel 的本机验证。

我遇到的问题是 Ajax 调用之前是这样验证的:

public function postRegisterAjax(A)
{
    try {
         ...
    } catch (ExceptionBag $e) {
        $msg = $e->getMessageBag()->all(':message');
        $status = Status::ERROR;
    }

    return $this->responseJson($status, $msg);
}

现在我介绍了UserValidationRequest 类,我希望 Ajax 调用向我抛出错误消息,而无需重新加载页面。为此,我需要将状态和消息作为 Json 响应转发。

我以某种方式尝试使用 after 验证挂钩来做到这一点,但它不起作用:

protected function getValidatorInstance()
{
    $validator = parent::getValidatorInstance();

    if ($validator->fails()) {
        \Log::info($validator->errors());

        $msg = $validator->errors();
        $status = Status::ERROR;

        return response()->json(['response' => [
            'status' => $status,
            'msg' => $msg,
        ]]);
    }

    return $validator;
}

代码在return response() 上失败,说Method passes does not exist (Illuminate/Support/Traits/Macroable.php:96)。

有谁知道这似乎是什么问题?

【问题讨论】:

    标签: php ajax laravel validation


    【解决方案1】:

    从 Laravel 5.x 版本(不确定)开始,failedValidation() 方法被引入到表单请求中,而不是 Laravel 4.x 中的 response()

    我通过在我的表单请求中覆盖该方法来定制响应以解决我的问题:

    public function failedValidation(Validator $validator)
    {
        if ($validator->fails()) {
            $status = Status::ERROR;
            throw new HttpResponseException(response()->json(["response" => [
                'msg'    => $validator->errors()->all(':message'),
                'status' => $status
            ]]));
        }
    
        return response()->json(["response" => [
            'msg'    => 'User successfully registered',
            'status' => Status::SUCCESS
        ]]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-27
      • 2015-05-10
      • 1970-01-01
      • 2014-05-31
      • 2017-04-11
      • 2018-02-18
      • 2014-08-31
      • 2017-05-30
      相关资源
      最近更新 更多