max_if
is a custom validation which is consists of reqired_if
and max
validations.
It is usable when you want to validate the size of a file when another field is equal to any value.
max_if:anotherfield,value,...
The field under validation must be present if the anotherfield field is equal to any value.
The field under validation must be less than or equal to a maximum value.
This validation just accepts file fields!
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('max_if', function($attribute, $value, $parameters) {
if (count($parameters) < 3) {
throw new InvalidArgumentException("Validation rule max_if requires at least 3 parameters.");
}
if ($value instanceof UploadedFile && $value->isValid() && $value instanceof File) {
return ($value->getSize() / 1024) <= $parameters[0];
}
return false;
});
Validator::replacer('max_if', function($message, $attribute, $rule, $parameters) {
return str_replace([':attribute', ':max'], [$attribute, $parameters[0]], $message);
});
}