Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Last active April 30, 2019 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtvbrianking/1dafa36ee6e711de3fb57fff1ed335ff to your computer and use it in GitHub Desktop.
Save mtvbrianking/1dafa36ee6e711de3fb57fff1ed335ff to your computer and use it in GitHub Desktop.
Laravel max allowed period validation

max_period:start_date,duration,metric

The difference betweent the field under validation, and the start_date field must not be greater than the specified duration in the given metric.

Metrics:

  • hours,
  • days*,
  • weeks,
  • months,
  • years

* default

Example

$this->validator($request, [
    'date_from' => 'date_format:Y-m-d',
    'date_to' => 'date_format:Y-m-d|after:date_from|max_period:date_from,2,days',
]);

Implementation

Validator::extend('max_period', function ($attribute, $value, $parameters, $validator) {
    $data = $validator->getData();

    $start = Carbon::parse($data[$parameters[0]]);
    $end = Carbon::parse($value);

    $duration = $parameters[1];
    $metric = array_get($parameters, 2, 'days');

    $method = studly_case('diffIn'.$metric);

    $diff = $start->$method($end);

    return $diff <= $duration;
}, 'Max allowed period is :duration :metric.');

Validator::replacer('max_period', function ($message, $attribute, $rule, $parameters) {
    return str_replace(
        [
            ':duration',
            ':metric',
        ], 
        [
            $parameters[1],
            array_get($parameters, 2, 'days'),
        ], 
        $message
    );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment