Laravel date validation erroring for string "today"

108 views Asked by At

I'm using laravel validation for a date field like this:

Validator::make($shipment, [
            'collection_date' => 'required|date',
    ...

and I'm sending json with this field:

"collection_date": "today",

It's giving this error:

{
    "collection_date": [
        "The collection date is not a valid date."
    ]
}

Now, you might say DUH, that's not a valid datestring, but the problem is this:

Every source I can find explaining how the "date" validator works in Laravel says it uses PHP's internal strtotime function. strtotime("today") spits out a timestamp corresponding to Today (specifically, 00:00 this morning). That being the case, "today" should be seen as a valid "date" by laravel, shouldn't it?

3

There are 3 answers

1
Othmane Nemli On BEST ANSWER

Laravel use parse_date() underhood is not using strtotime() function You can check the validateDate function for more info If you want to use your rule you can go with that

$validator = Validator::make($shipment, [
    'collection_date' => [
        'required',
        function (string $attribute, mixed $value, Closure $fail) {
            if (strtotime($value) === false) {
                $fail("The {$attribute} is invalid.");
            }
        },
    ],
])

Or you can make your own rule validation

If you are not satisfied with date rule you can override it by extending the Validator

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Validator::extend('date', function ($attribute, $value, $parameters, $validator) {
            return !!strtotime($value);
        });
    }
}

// Then

$validator = Validator::make($shipment, [
    'collection_date' => [
        'required',
        'date'
    ],
])

3
Wolf_Developer On

The validator is treating the 'today' sent in the json as a string and not a validate date format. When using the date rule, Laravel expects the field value to be in a format that directly represents a date, such as "Y-m-d" (e.g., "2023-10-31") or "m/d/Y" (e.g., "10/31/2023"). While PHP's strtotime function is forgiving and interprets "today" correctly, Laravel's date rule does not consider such string representations as valid date formats.

"collection_date": "2023-10-31",
0
nidhinnp On
 $jsonData = [
        [
            'collection_date' => Carbon::now()->format('Y-m-d'),
        ],

        // Add more data as needed
    ];