Yii2 image dimension validation

Azraar Azward picture Azraar Azward · Feb 18, 2016 · Viewed 8.2k times · Source

This validation line doesn't work. i could upload images in any dimension.

['image', 'image', 'minWidth' => 250, 'maxWidth' => 250,'minHeight' => 250, 'maxHeight' => 250], 

in the controller, i use.

 $image = UploadedFile::getInstance($this, 'image');

Answer

Jørgen picture Jørgen · Feb 18, 2016

There's nothing wrong with the last line as far as I can see. https://github.com/yiisoft/yii2/blob/master/docs/guide/tutorial-core-validators.md#yiivalidatorsimagevalidatorimage-

But you're declaring rules for the image attribute twice - one as a file, and one as a image. The image validator extends from the file validator, so it inherits all its properties.

Image Validator (docs):

This validator checks if the input value represents a valid image file. It extends from the file validator and thus inherits all its properties. Besides, it supports the following additional properties specific for image validation purpose:

Try combining it in to one rule, and see if that helps.

[
     'image', 
     'image', 
     'minWidth' => 250, 
     'maxWidth' => 250,
     'minHeight' => 250, 
     'maxHeight' => 250, 
     'extensions' => 'jpg, gif, png', 
     'maxSize' => 1024 * 1024 * 2
],

Edit: And you need to save the image in the $model, like $model->imagefor it to be validated through the model validation rules if you're in the controller.

Here is a good example: http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html