2017-12-18 623 views
1

我的Laravel 4.2项目的验证是使用Ardent包完成的。在去Laravel 5.5之后,我已经取消了Ardent,并希望通过表单请求来完成Laravel的本地验证。Laravel自定义验证和ajax

我的问题是,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响应。

不知何故,我想这样做与验证挂钩后,但它不工作:

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 existIlluminate/Support/Traits/Macroable.php:96)。

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

回答

0

从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 
    ]]); 
} 

我通过重写该方法在我的形式要求定制我的需求响应解决了我的问题