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

Jus*_*tin 6 php validation laravel

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

'password' => 'required|confirmed|min:8',
Run Code Online (Sandbox Code Playgroud)

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

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

pet*_*erm 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());
}
// ...
Run Code Online (Sandbox Code Playgroud)


Tun*_*gac 9

你应该设计你的表格如下;

<input type="password" name="password">
<input type="password" name="password_confirmation">
Run Code Online (Sandbox Code Playgroud)

来自 Laravel 的引用:已确认 “验证中的字段必须具有匹配的 foo_confirmation 字段。例如,如果验证中的字段是密码,则输入中必须存在匹配的 password_confirmation 字段”

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

$request->validate([
        "password" => 'required|confirmed' 
    ]);
Run Code Online (Sandbox Code Playgroud)

  • 好吧,我们的质量保证人员不同意这一点。他坚持认为,如果错误消息显示“密码确认与密码不匹配”,那么它应该显示在确认字段下而不是密码字段下。我想,这是主观的,但我有点明白他的观点 - 这是确认错误而不是密码。 (3认同)