2012-10-14 60 views
1

我试图验证字段,如果文件字段不是空的。因此,如果有人试图上传文件,我需要验证其他字段以确保他们选择了正在上传的内容,但我不知道如何检查以查看,或仅在字段不为空的情况下运行规则。验证另一个字段,如果文件字段不为空

public function rules() 
{ 
    // NOTE: you should only define rules for those attributes that 
    // will receive user inputs. 
    return array(
     array('full_name, gender_id','required'), 
     array('video', 'file', 'types'=>'mp4', 'allowEmpty' => true), 
     array('audio', 'file', 'types'=>'mp3', 'allowEmpty' => true), 
     array('video','validateVideoType'), 
    ); 
} 

public function validateVideoType() { 
    print_r($this->video); 
    Yii::app()->end(); 
} 

所以this->video总是空的,不管我是否上传了一些东西。如何检查该变量是否已设置?

回答

2

自定义验证功能必须正确定义。它总是有两个参数$attribute & $params

public function validateVideoType($attribute, $params) { 
    print_r($this->video); 
    Yii::app()->end(); 
} 

现在在这里你应该写你自定义的方式来验证。 我相信,这将工作正常。

+0

谢谢,但$ params总是回来作为一个空阵列...? – keeg

+0

$ params是规则中定义的其他参数,如消息。 –

0

您可以用jQuery/javascript检查它,其中'new_document'是输入文件字段的名称。

if ($("#new_document").val() != "" || $("#new_document").val().length != 0) { 
     //File was chosen, validate requirements 
     //Get the extension 
     var ext = $("#new_document").val().split('.').pop().toLowerCase(); 
     var errortxt = ''; 
     if ($.inArray(ext, ['doc','docx','txt','rtf','pdf']) == -1) { 
      errortxt = 'Invalid File Type'; 
      //Show error 
      $("#document_errors").css('display','block'); 
      $("#document_errors").html(errortxt); 

      return false; 
     } 

     //Check to see if the size is too big 
     var iSize = ($("#new_document")[0].files[0].size/1024); 
     if (iSize/1024 > 5) { 
      errortxt = 'Document size too big. Max 5MB.'; 
      //Show error 
      $("#document_errors").css('display','block'); 
      $("#document_errors").html(errortxt); 

      return false 
     } 
    } else { 
     //No photo chosen 
     //Show error 
     $("#document_errors").css('display','block'); 
     $("#document_errors").html("Please choose a document."); 
     return false; 
    } 

这段代码显然不是完美的满足您的需求,但可能有需求拼凑你所需要的东西。