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
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.
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
Or you can make your own rule validation
If you are not satisfied with date rule you can override it by extending the Validator