Laravel 5.3 变量为空时验证失败
Laravel 5.3 Validation Fails when Variables are Null
自从 laravel 从 5.1 升级到 5.3 后,我在验证方面遇到了几个奇怪的问题。
当我post这样的数据时:
firstName null
验证规则是这样的:
$validator = Validator::make($postData, [
'firstName' => 'string|max:255',
'lastName' => 'string|max:255'
]);
以上失败并显示类似 "The XYZ must be a string."
的消息。我不明白的是:
为什么没有设置为required
时验证失败?
意思是,如果值为
空着对吧?
为什么设置为null
会验证失败?
为什么根本不发送参数就验证失败?
(就像根本没有 post 编辑的 lastName
)
Laravel 5.3 验证有什么变化吗?
添加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 null
values.
当您想要必需但值本身可以为空,如空字符串时。
Validator::make($postData, [
'firstName' => 'present|string|max:255|nullable',
'lastName' => 'present|string|max:255|nullable'
]);
在像“笔记”这样的场景中很有用,可以通过从所有文本中删除输入字段并点击保存来清空笔记。
自从 laravel 从 5.1 升级到 5.3 后,我在验证方面遇到了几个奇怪的问题。
当我post这样的数据时:
firstName null
验证规则是这样的:
$validator = Validator::make($postData, [
'firstName' => 'string|max:255',
'lastName' => 'string|max:255'
]);
以上失败并显示类似 "The XYZ must be a string."
的消息。我不明白的是:
为什么没有设置为
required
时验证失败? 意思是,如果值为 空着对吧?为什么设置为
null
会验证失败?为什么根本不发送参数就验证失败? (就像根本没有 post 编辑的
lastName
)
Laravel 5.3 验证有什么变化吗?
添加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 containnull
values.
当您想要必需但值本身可以为空,如空字符串时。
Validator::make($postData, [
'firstName' => 'present|string|max:255|nullable',
'lastName' => 'present|string|max:255|nullable'
]);
在像“笔记”这样的场景中很有用,可以通过从所有文本中删除输入字段并点击保存来清空笔记。