Skip to content

Instantly share code, notes, and snippets.

@mehrancodes
Created March 15, 2017 11:18
Show Gist options
  • Save mehrancodes/528e8d537738b3f8b8fb9fbd5f86b8be to your computer and use it in GitHub Desktop.
Save mehrancodes/528e8d537738b3f8b8fb9fbd5f86b8be to your computer and use it in GitHub Desktop.
Custom validation max_if

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);
        });
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment