Laravel 5.4 有时验证规则不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42039416/
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:16:02  来源:igfitidea点击:

Laravel 5.4 sometimes validation rules not working

laravellaravel-validationlaravel-5.4

提问by Munna Khan

I am trying to validate a date field only if it is present. It was working fine before I upgraded from Laravel 5.2 to 5.4

我试图仅在日期字段存在时才对其进行验证。在我从 Laravel 5.2 升级到 5.4 之前它运行良好

In Laravel 5.2 this rules works fine:

在 Laravel 5.2 中,这条规则可以正常工作:

public function rules()
{
    return [
        'available_from' => 'date',
    ];

}

In 5.4 it returns validation error The available from is not a valid date.I tried this new rules

在 5.4 它返回验证错误The available from is not a valid date.我尝试了这个新规则

public function rules()
{
    return [
        'available_from' => 'sometimes|date',
    ];

}

Still got the same error and seems the sometimesrules not affecting the validation at all. How can I get rid of this error?

仍然出现相同的错误,似乎sometimes规则根本不影响验证。我怎样才能摆脱这个错误?

I don't understand why Laravel changed something that was working before!!!

我不明白为什么 Laravel 改变了一些以前有效的东西!!!

回答by ikurcubic

The problem occurs because of \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class in Http\Kernel.php.

出现问题的原因是 Http\Kernel.php 中的 \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class。

When you submit empty date field this middleware converts empty string to null. Then validation returns not valid date error. You can check docsfor more details.

当您提交空日期字段时,此中间件会将空字符串转换为 null。然后验证返回无效日期错误。您可以查看文档以获取更多详细信息。

It can be fixed with nullable

它可以用nullable修复

public function rules()
{
    return [
        'available_from' => 'sometimes|nullable|date',
    ];

}

From Laravel docs:

来自Laravel 文档

nullable

The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values.

可空的

验证中的字段可能为空。这在验证可包含空值的字符串和整数等原语时特别有用。