skip to Main Content

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

Answers


  1. 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",
    
    Login or Signup to reply.
  2.  $jsonData = [
            [
                'collection_date' => Carbon::now()->format('Y-m-d'),
            ],
    
            // Add more data as needed
        ];
    
    Login or Signup to reply.
  3. 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'
        ],
    ])
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search