File Validation

I am using a file field for creating a address model. The file will support extensions( png, gif, jpeg). But when i select another extension file it it shows "field cannot be blank" error.

Address model




public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('name', 'required'),

			array('name, address', 'length', 'max'=>55),

                        array('address', 'file', 'types'=>'jpg, jpeg, png','allowEmpty'=>false),

			// The following rule is used by search().

			// Please remove those attributes that should not be searched.

			array('id, name, address', 'safe', 'on'=>'search'),

		);

	}



Controller action




public function actionCreate()

	{

		$model=new Address;


		// Uncomment the following line if AJAX validation is needed

		 $this->performAjaxValidation($model);


		if(isset($_POST['Address']))

		{

                    $model->attributes=$_POST['Address'];

                       $up= CUploadedFile::getInstance($model,'address');  

                       $model->address=$up;

                       $model->validate();

                       if($model->save())

                           {

                       

                        $up->saveAs($_SERVER['DOCUMENT_ROOT'].Yii::app()->request->baseUrl.'/css/'.$up);  // image will uplode to rootDirectory/banner/

                        $this->redirect(array('view','id'=>$model->id));

                           }

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}




_form.php




<div class="form">


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'address-form',

	'enableAjaxValidation'=>true,

        'htmlOptions' => array('enctype' => 'multipart/form-data'),

        'clientOptions'=>array('validateOnSubmit'=>true),

)); ?>


	<p class="note">Fields with <span class="required">*</span> are required.</p>


	<?php echo $form->errorSummary($model); ?>


	<div class="row">

		<?php echo $form->labelEx($model,'name'); ?>

		<?php echo $form->textField($model,'name',array('size'=>55,'maxlength'=>55)); ?>

		<?php echo $form->error($model,'name'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'address'); ?>

		<?php echo $form->fileField($model,'address'); ?>

		<?php echo $form->error($model,'address'); ?>

	</div>


	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>


<?php $this->endWidget(); ?>


</div><!-- form -->



  1. When i am using form without popup dialog box

when i change ‘enableAjaxValidation’=>true, to false the validation is correct - “file format error”.

  1. When i am using popup dialog box for creating a model

when i change ‘enableAjaxValidation’=>true, to false the form window is closed without showing error.

when ‘enableAjaxValidation’=>true, - the form will show “cannot be blank error”

I want to show file validation error in popup dialog box.

How it solve?

Thanks.

hi,


 return array(

        array('file', 'files', 'types'=>'pdf')

       );

hi Ghanshyam, I can’t get you… What you mean with this array (‘file’, ‘files’, ‘types’=>‘pdf’)?

I added the file type in model rules.

Thanks.

You can’t upload a file via AJAX, so you can’t validate it either. Maybe you can get away with using client validation just for the file field.

How it can solve…?

can give you a script for file upload where i have manually done file field validation…

view file




$form=$this->beginWidget('CActiveForm', array(

		'id'=>'roster-main-form',

		'enableAjaxValidation'=>true,

		'clientOptions'=>array('validateOnSubmit'=>true),

		'htmlOptions'=>array('enctype' => 'multipart/form-data'),

	));






<div class="row" id="fileUpload">

		<?php echo $form->labelEx($model,'uploadFile<span style="color:red">&nbsp;*</span>'); ?>

		<?php echo $form->fileField($model,'uploadFile',array('style'=>'width:200px;','onChange'=>'checkFile()','title'=>'Only xls allowed'));?>

		<div id="filecheck" style="color: red;font-size:0.9em;"></div>

		<?php //echo $form->error($model,'uploadFile',array('style'=>$styleDataError.';margin-top:20px;')); ?> 

		<?php echo CHtml::hiddenField('errorVal','0');?>

	</div>






<?php 

$this->widget('bootstrap.widgets.TbButton', array(

				'label'=>Yii::t('zii','Create'),

				'buttonType' => 'submit',

				'url'=>array('create'),

				'type'=>'primary',

				'icon'=>'ok white',

				'htmlOptions'=>array('onClick'=>'return checkFileUpload()'),

			)); 

?>






<script type="text/javascript">

function checkFile(){

  var ext = $('#RosterMain_uploadFile').val().split('.').pop().toLowerCase();

  

  //if(val == 1){

  	if!((($.inArray(ext, ['xls']) == -1)||($.inArray(ext, ['xlsx']) == -1))) {

        //$("#filecheck").addClass("flash-error");

		$("#filecheck").html("The "+ext+" format is not allowed. Please upload excel file only!");

    	$('#RosterMain_uploadFile').val('');

		$("#fileUpload").removeClass("row");

		$("#fileUpload").addClass("row error");

		$('#submitPassive').show();

		$('#submitActive').hide();

	}  else {

  	   // $("#filecheck").removeClass("flash-error");

		$("#fileUpload").removeClass("error row");

		 $("#fileUpload").addClass("row success");

		$('#errorVal').val(0);

        $("#filecheck").html("");

		$('#submitPassive').hide();

		 $('#submitActive').show();

		 //return true;

	} 

 // }

}

function checkFileUpload(){

	if($('#RosterMain_uploadFile').val()==''){

		$("#filecheck").html("Please select file to upload");

		$("#fileUpload").removeClass("row");

		$("#fileUpload").addClass("row error");

		return false;

	}else{

		return true;

	}

}

</script>