Laravel 5.3 Validation Fails when Variables are Null
Asked Answered
H

2

53

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?

Hipparchus answered 7/11, 2016 at 12:33 Comment(0)
B
113

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.

Beckham answered 7/11, 2016 at 12:35 Comment(4)
Perfect. That fixed it. Thank you! I will accept your answer in 10 mins once SO allows me to. A quick question, did this change in laravel 5.3? Cuz I did not get this issue in 5.1 and I never added nullable in validation rules.Hipparchus
@Hipparchus don't see any code for nullable rule in 5.2. It's in 5.3 only. So I guess they changed something in validation.Beckham
That makes sense. Thank you so much @Alexey for pointing this out. It was very helpful!Hipparchus
doesn't work for datesGettings
F
9

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.

Forego answered 26/6, 2020 at 14:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.