Laravel 5.4 sometimes validation rules not working
Asked Answered
F

1

20

I am trying to validate a date field only if it is present. It was working fine before I upgraded from Laravel 5.2 to 5.4

In Laravel 5.2 this rules works fine:

public function rules()
{
    return [
        'available_from' => 'date',
    ];

}

In 5.4 it returns validation error The available from is not a valid date. I tried this new rules

public function rules()
{
    return [
        'available_from' => 'sometimes|date',
    ];

}

Still got the same error and seems the sometimes rules not affecting the validation at all. How can I get rid of this error?

I don't understand why Laravel changed something that was working before!!!

Flavouring answered 4/2, 2017 at 10:44 Comment(2)
What is the format you are using for date?Refund
I use this format YYYY-MM-DDFlavouring
M
49

The problem occurs because of \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class in Http\Kernel.php.

When you submit empty date field this middleware converts empty string to null. Then validation returns not valid date error. You can check docs for more details.

It can be fixed with nullable

public function rules()
{
    return [
        'available_from' => 'sometimes|nullable|date',
    ];

}

From Laravel docs:

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.

Maurice answered 4/2, 2017 at 13:46 Comment(3)
Wonderful help. Work perfectly in Laravel 5.6 also.Lesbianism
I'm getting the same "is not a valid date" and I'm always sending dates like "2018-03-05" through PostmanDemoralize
You just literally saved my day.Cancel

© 2022 - 2024 — McMap. All rights reserved.