Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 sometimes validation rules not working

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!!!

like image 897
Munna Khan Avatar asked Feb 04 '17 10:02

Munna Khan


1 Answers

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.

like image 120
ikurcubic Avatar answered Sep 20 '22 07:09

ikurcubic