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:
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?
Why does the validation fail if the value is set as null
?
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?
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 containnull
values.
When you want something to be required but the value itself can be empty, like an empty string.
Validator::make($postData, [
'firstName' => 'present|string|max:255|nullable',
'lastName' => 'present|string|max:255|nullable'
]);
Useful in scenarios like "notes", which can be emptied by removing the input field from all its text and hit save.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With