2015-06-22 159 views
2

想檢查我已經做了一個CustomValidator.php處理所有我的額外驗證規則,但問題是我應該如何返回自定義錯誤消息?這是我做我的CustomValidator.php文件,Laravel 5自定義驗證規則消息錯誤

<?php namespace App\Validators\CustomValidator; 

use Illuminate\Validation\Validator; 
use Auth; 

class CustomValidator extends Validator 
{ 
    public function validateVerifyPassword($attribute, $value, $parameters) 
    { 
     $currentUser = Auth::user(); 
     $credentials = array ('email' => $currentUser->email, 'password' => $currentUser->password); 

     return Auth::validate($credentials); 
    } 

    protected function replaceVerifyPassword($message, $attribute, $rule, $parameters) 
    { 
     return str_replace($attribute, $parameters[0], $message); 
    } 
} 

,這是我在如何定義FormRequest.php我的自定義錯誤消息

public function messages() 
{ 
    return [ 
     'login_email.required'    => 'Email cannot be blank', 
     'old_password.required'    => 'You need to provide your current password', 
     'old_password.between'    => 'Your current password must be between :min and :max characters', 
     'old_password.verifyPassword'  => 'Invalid password', 
     'password.required'     => 'Password is required.', 
     'password.between'     => 'Your password must be between :min and :max characters', 
     'password_confirmation.required' => 'You need to retype your password', 
     'password_confirmation.same'  => 'Your new password input do not match', 
     'g-recaptcha-response.required'  => 'Are you a robot?', 
     'g-recaptcha-response.captcha'  => 'Captcha session timeout' 
    ]; 
} 

注意的是,驗證部分工作,只有它不會通過自定義錯誤消息,並且它與

CustomValidator.php line 18: 
Undefined offset: 0 

一個錯誤是在$parameter[0]部分還給我

回答

6

找到了解決方案,顯然當您嘗試執行驗證時,它顯示的錯誤消息將攜帶該驗證規則的錯誤消息的關鍵。我們用下面的圖片爲例,

Validate

注意,在電子郵件字段下,有一個錯誤消息validation.current_email錯誤,current_email是用來在FormRequest指定您的自定義錯誤消息的關鍵。所以基本上你要做的就是在我的FormRequest.php,我添加了錯誤消息喜歡這樣:

public function messages() 
{ 
    return [ 
     'new_email.required'    => 'New email cannot be blank', 
     'new_email.current_email'   => 'This is the current email adderess being used', 
     'password.required'     => 'You need to provide your current password', 
     'password.between'     => 'Your current password must be between :min and :max characters', 
     'password.verify_password'   => 'Invalid password', 
     'g-recaptcha-response.required'  => 'Are you a robot?', 
     'g-recaptcha-response.captcha'  => 'Captcha session timeout' 
    ]; 
} 

,這將是在下面的圖像的最終結果:

final outcome