2012-10-14 4 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는 message와 같은 규칙에 정의 된 다른 매개 변수입니다. –

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; 
    } 

이 코드는 분명히 사용자의 요구에 완벽하지는 않지만 필요한 항목을 조합 할 수있는 요구 사항이있을 수 있습니다.

관련 문제