How To Detect If A Validation Failed

I have a form field for image upload. A validation rule for it is defined as follows:

array('imagefile', 'file', 'types' => 'jpg, gif, png', 'maxSize' => 1024 * 50, 'allowEmpty' => true),

It works ok in a sense that if I try to upload too big file, it shows error message. Yet, the preview form tries to show the image from interrupted upload. Here is the code from preview:

<?php if(!empty($model->imagefile) && !$model->hasErrors('imagefile')) { ?>

<img src="<?php echo CController::createUrl('product/thumb').'/'.$model->category_id.'/'.$model->id; ?>" alt="<?php echo $model->name; ?>" />

<?php } ?>

As you may see, I check if imagefile attribute hasErrors, but it seems not reporting any error because I see an empty rendered image placeholder.

What’s wrong and how to fix this?

Thanks in advance.

In your validation rule, set ‘allowEmpty’ to false.


‘allowEmpty’ is set to true so, if the user does not upload a file, there’ll be no error. If you don’t want to force users to upload a file, leave the ‘allowEmpty’ as false and remove the !$model->hasErrors(‘imagefile’).