Search code examples
phplaraveldatetimelaravel-validation

Laravel date validation erroring for string "today"


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?


Solution

  • 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'
        ],
    ])