Laravel 5.3 Validation Fails when Variables are Null

怎甘沉沦 提交于 2019-12-04 16:46:54

问题


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

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:

  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 lastName which is not posted at all)

Has something changed in Laravel 5.3 validations?


回答1:


Add nullable rule:

'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.



来源:https://stackoverflow.com/questions/40465297/laravel-5-3-validation-fails-when-variables-are-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!