Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 image dimension validation

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');
like image 384
Azraar Azward Avatar asked Feb 18 '16 05:02

Azraar Azward


1 Answers

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

like image 56
Jørgen Avatar answered Oct 21 '22 17:10

Jørgen