Search code examples
formslaravelvalidationinputcustom-validators

How to make a validation on a calculated field in laravel 5.5


I want to know how to validate the calculated value of a input field .

For example I have a field named birthDate I want to accept the date only if the calculated age from birthDate is less than 16 .

I want to make the validation within a custom Request class

Thank you.


Solution

  • Validator::extend('youngerThan', function($attribute, $value, $parameters)
    {
        $maxAge = ( ! empty($parameters)) ? (int) $parameters[0] : 16;
    
        //return (new DateTime)->diff(new DateTime($value))->y <= $minAge;
    
    
    
        // or the same using Carbon
    
        $dob = new Carbon\Carbon($value);
    
        return $dob->age >= $minAge;
    });
    

    This way you can use the rule for any age you like:

    $rules = ['dob' => 'youngerThan']; 
    $rules = ['dob' => 'youngerThan:15'];