2017-12-18 625 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 
    ]]); 
} 

我通過重寫該方法在我的形式要求定製我的需求響應解決了我的問題