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

时间:2015-06-22 02:09:16

标签: 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);
    }
}

这就是我在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]部分

1 个答案:

答案 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