当变量为空时 Laravel 5.3 验证失败

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

Laravel 5.3 Validation Fails when Variables are Null

laravelvalidationlaravel-5.3laravel-validation

提问by Neel

Since upgrading laravel from 5.1 to 5.3, I've got couple of odd issues with Validation.

自从将 laravel 从 5.1 升级到 5.3 以来,我在验证方面遇到了一些奇怪的问题。

When I post a data like this:

当我发布这样的数据时:

firstName    null

And the validation rules are like this:

验证规则是这样的:

$validator = Validator::make($postData, [
              'firstName'           => 'string|max:255',
              'lastName'            => 'string|max:255'
            ]);

The above fails with the messages something like "The XYZ must be a string.". What I don't understand is:

以上失败,消息类似于"The XYZ must be a string.". 我不明白的是:

  1. Why is the validation failing when it is not set as required? Meaning, it should ignore it and not throw an error if the value is empty, right?

  2. Why does the validation fail if the value is set as null?

  3. Why does the validation fail when the parameter is not sent at all? (like the lastNamewhich is not posted at all)

  1. 为什么未设置为时验证失败required?意思是,如果值为空,它应该忽略它并且不会抛出错误,对吗?

  2. 如果将值设置为 ,为什么验证会失败null

  3. 为什么在根本不发送参数时验证失败?(就像lastName根本没有发布的)

Has something changed in Laravel 5.3 validations?

Laravel 5.3 验证中有什么变化吗?

回答by Alexey Mezenin

Add nullablerule:

添加nullable规则:

'firstName' => 'string|max:255|nullable',
'lastName' => 'string|max:255|nullable'

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

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