Search code examples
phplaravelvalidationlaravel-9

How to add Multiple Dimenstion for single image validation in Laravel Validation


I'm working on validating an image file with two different dimensions rule, it can b Icon or Banner depending on the selection of recently selected field. I'm doing this by adding a custom Rule class, here is my validation rule which works fine on Icon Only OR Banner Only

$validator = Validator::make([
        'file' => $value,
    ], [
        'file' => 'mimes:png,webp|dimensions:width=512,height=512|max:2048'
    ]);
$validator->validate();

now the problem is to validate the banner with a different dimension in the same field. Is there any way to add another Width & Height to this line? I've tried to add another rule under this file with the same name, but it doesn't work. Or is there any other approach to solve this problem? I've read the documentation but could not find the solution there.

Thanks in advance.


Solution

  • Validation rules by default must all pass for the input to be valid. In your case you need one of the two rules to pass which is not possible via built-in validation rules. You can create your own validation rule e.g.:

    php artisan make:rule DimensionRule
    

    Then modify the generated rule:

    class DimensionRule implements Rule {
    
        public function passes($attribute, $value) {
           $validator1 = Validator::make([ $attribute => $value ], [ $attribute => 'dimensions:width=512,height=512' ]);
           if ($validator1->passes()) { 
              return true;
           }
           $validator2 = Validator::make([ $attribute => $value ], [ $attribute => 'dimensions:width=800,height=30' ]);
           return $validator2->passes();        
        }
    
        public function message()
        {
            return 'Dimensions must either be 512x512 or 800x30';
        }
    }
    

    Then you can use this rule:

    $validator = Validator::make([
            'file' => $value,
        ], [
            'file' => [ 'mimes:png,webp', new DimensionRule(), 'max:2048' ]
        ]);
    $validator->validate();