如何使Laravel'确认'验证器将错误添加到确认字段?

时间:2015-05-11 14:29:59

标签: php validation laravel

默认情况下,Laravel'确认'验证器将错误消息添加到原始字段,而不是通常包含已确认值的字段。

'password' => 'required|confirmed|min:8',

是否有任何简单的方法来扩展验证器或使用某些技巧强制它始终在确认字段而不是原始字段上显示错误?

如果我输入密码两次失败,错误似乎更适合属于确认字段而不是原始密码字段。或许这只是我们的UX分析师得到的挑剔......

4 个答案:

答案 0 :(得分:14)

一种方法是使用same规则而不是confirmed

// ...

$input = Input::all();

$rules = [
    'password' => 'required|min:8',
    'password_confirmation' => 'required|min:8|same:password',
];

$messages = [
    'password_confirmation.same' => 'Password Confirmation should match the Password',
];
$validator = Validator::make($input, $rules, $messages);

if ($validator->fails()) {
    return back()->withInput()->withErrors($validator->messages());
}
// ...

答案 1 :(得分:3)

您应按以下方式设计表单;

<input type="password" name="password">
<input type="password" name="password_confirmation">

Laravel的语录:已确认 “正在验证的字段必须具有匹配的foo_confirmation字段。例如,如果正在验证的字段是password,则在输入中必须存在匹配的password_confirmation字段”

现在,您可以按照以下方式设计验证;

$request->validate([
        "password" => 'required|confirmed' 
    ]);

答案 2 :(得分:1)

快速想到的一个解决方案就是在password字段上显示password_confirmation错误。

如果这对您不起作用,只需将password_confirmation字段标记为密码,将password字段标记为密码确认,这样如果有错误,它会显示在{{1附近标签而不是password_confirmation标签。

否则,添加自己的自定义验证方法并不困难。

答案 3 :(得分:1)

$rules=[
            'username'=>'required|max:20',
            'password1'=>'required|min:8',
            'password2'=>'required|min:8|same:password1',
        ];
        $error_messages=[
            'password2.same'=>'password are not the same password must match same value',
            'password1.min'=>'password length must be greater than 8 characters',
            'password2.min'=>'confirm-password length must be greater than 8 characters',


        ];
        $validator=  validator($request->all(), $rules, $error_messages);
        if ($validator->fails()) {
            return redirect('control_pannel/change_password')
                        ->withErrors($validator)
                        ->withInput();
       }