I did a custom Validation Rule that iterates over an array of objects that contains a key dates and check if those dates are consecutives (the difference between dates are just 1 day). For that, I need the 'day' key to be filled and have a correct date format. I put the date_format validator rule in the day key but as my custom Rule is in the array field It crash when I don't give him a correct date_format (for example a random string). Maybe you understan better with the code.
Custom Validator Rule
Validator::extend('consecutive_dates', function($attribute, $value, $parameters, $validator) {
// Order the in the array with the 'day' value
usort($value, array($this, 'compare_dates'));
$previous_date = null;
foreach ($value as $date) {
// Check if dates are consecutives
$current_date = new DateTime($date['day']);
if ($previous_date !== null) {
$interval = $current_date->diff($previous_date);
if ($interval->days !== 1) {
// If not, fails
return false;
}
}
$previous_date = $current_date;
}
return true;
);
Rules definition
'dates.*.day' => 'required_with:dates|date_format:Y-m-d',
'dates' => 'bail|array|filled|consecutive_dates',
Now if I try to validate something like this:
"dates": [{
"day": "fdsa",
}]
It will crash and say
DateTime::__construct(): Failed to parse time string (fdsa) at position 0 (f): The timezone could not be found in the database
The question is: Is there a way to tell Laravel to first Validate that the 'dates.*.day' must have date_format: Y-m-d so It won't fail on the custom validation?