如果为空,Laravel 密码验证将在“最小长度”上失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43873103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:56:09  来源:igfitidea点击:

Laravel password validation fail on "min length" if empty

phplaravelvalidation

提问by kuchar

My validator rule looks like this:

我的验证器规则如下所示:

$validator = Validator::make($request->all(), [
        'name'     => 'required|min:5|max:255',
        'email'    => [
            'required',
            'max:255',
            'email',
            Rule::unique('users')->ignore($id),
        ],
        'password' => 'min:6|confirmed',
    ], [
        'confirmed' => 'Has?o musi si? zgadza?',
        'unique'    => 'Wpisz inny adres email, ten adres jest zaj?ty',
        'required'  => 'To pole jest wymagane.',
        'min'       => 'To pole musi mie? minimum :min znaków.',
    ]);

    if ($validator->fails()) {
        return redirect('/panel/users/'.$id.'/edit')
            ->withErrors($validator)
            ->withInput();
    }

When i edit user without change password, validator fails with 'min' rule. As you can see my validator doesnt require password, so why it validating?

当我在不更改密码的情况下编辑用户时,验证器因“最小”规则而失败。正如您所看到的,我的验证器不需要密码,那么为什么要验证呢?

采纳答案by Adam W.

It's look like what you want.

它看起来像你想要的。

$validator->sometimes('password', 'min:6|confirmed', function ($input) {
    return (strlen($input->password) > 0);
});

回答by user947668

use nullable rule

使用可为空规则

'nullable|min:6|confirmed'

回答by Ian

You are coming across expected behaviour.

您遇到了预期的行为。

min:value

最小值:值

The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

验证中的字段必须具有最小值。字符串、数字和文件的计算方式与大小规则相同。

as per the docs.

根据文档

You can use the sometimesrule

你可以使用sometimes规则

Validator::make($request->all(), [
    'password' => 'sometimes|min:6|confirmed',
]

回答by Alex Harris

You can use sometimesfor this case:

您可以sometimes在这种情况下使用:

$this->validate($request, [
    'password' => 'sometimes|min:6',
]);

You can read more about sometimeshere:

您可以sometimes在此处阅读更多信息:

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:

在某些情况下,您可能希望仅当输入数组中存在该字段时才对该字段运行验证检查。要快速完成此操作,请将有时规则添加到您的规则列表中:

confirmedseems as if it can also cause a problem. So try doing it manually:

confirmed似乎它也会引起问题。因此,请尝试手动执行此操作:

'password' => 'required|min:6',
'password_confirmation' => 'required|min:6|same:password',