Laravel 5自定义验证规则消息错误

Ken*_*Yap 2 laravel laravel-5 laravel-validation

想检查我已经制作了一个CustomValidator.php来处理我所有的额外验证规则,但问题是我应该如何返回自定义错误消息?这是我为我的CustomValidator.php文件做的,

<?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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是我在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'
    ];
}
Run Code Online (Sandbox Code Playgroud)

注意到验证部分正在工作,只是它不会传递自定义错误消息,它返回我的错误

CustomValidator.php line 18:
Undefined offset: 0
Run Code Online (Sandbox Code Playgroud)

在这$parameter[0]部分

Ken*_*Yap 6

找到解决方案,显然当您尝试执行验证时,它出现的错误消息将携带该验证规则的错误消息的密钥.我们以下面的图像为例,

验证

请注意,在电子邮件字段下,出现错误消息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'
    ];
}
Run Code Online (Sandbox Code Playgroud)

这将是下图中的最终结果:

最终结果