1

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?

1 Answer 1

0

You should check given value is valid date or not firstly, like this

if (Carbon::createFromFormat('date format', $date['day']) !== false) {
        // valid date
}

I hope this will help.

Sign up to request clarification or add additional context in comments.

2 Comments

Do you mean in my custom validation? I know i can check it in the custom validation but I already have that validation with date_format:Y-m-d so I didn't want to repeat myself. That's why I was wondering if there was something like an order of rules in Laravel or I have to check it again.
yes, I mean check your custom validation, Can you check these params $attribute, $value, $parameters, $validator on custom controller, Maybe these are consist date format, so you don't repeat yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.