Search code examples
laravellaravel-5laravel-validation

Laravel Custom Validation Order


I add a custom Validation Rule

Validator::extend('validate_timezone', function($attribute, $value, $parameters, $validator) {
    $items = request('items');
    $from_date = Carbon::createFromFormat('Y-m-d H:i:s', $item['from_date']);
    // my code below depend on $from_date
    ......
    ......

    return true;
);

validation rule

 "from_date" => "required|date_format:Y-m-d H:i:s|validate_timezone",

The problem, custom validation validate_timezone run before 'date_format:Y-m-d H:i:s', so if the format of date is wrong, I will get error inside validate_timezone function

How can I force to validate date_format:Y-m-d H:i:s before the custom validation validate_timezone?


Solution

  • In the documentation the following can be found:

    Rules will be validated in the order they are assigned.

    Meaning the code is working as expected. You're probably looking for the bail option:

    Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute

    Which would mean you should try this:

    "from_date" => "bail|required|date_format:Y-m-d H:i:s|validate_timezone",