Custom validation rule for partial percentages sum

Submitted by alariva - 6 years ago

Sometimes we need to validate that several fields that are partial percentages don't sum up over the 100%. It is possible to achieve this with a custom validation rule and then using it on each partial, indicating the other fields as arguments.

// AppServiceProvider.php (or your preferred)

use Validator;

    // ...

    // Extend the validation rule with the custom rule called 'percentage'
    
    public function boot()
    {
        Validator::extend('percentage', function ($attribute, $value, $parameters, $validator) {
    
            $sum = 0;
            foreach ($parameters as $key => $attributeName) {
                $attributeValue = array_get($validator->getData(), $attributeName);
                $sum += floatval($attributeValue);
            }
            $sum += floatval($value);
    
            return $sum <= 100;
        });
    }

    // ...

// In your controller, or wherever you build your validation set

// ...

            'body_fat'        => 'numeric|max:100|min:0|percentage:skeletal_muscle,rest',
            'skeletal_muscle' => 'numeric|max:100|min:0|percentage:body_fat,rest',
            'rest'            => 'numeric|max:100|min:0|percentage:body_fat,skeletal_muscle',

// ...