2011-03-03 125 views
8

我想知道是否有一種方法來驗證CodeIgniter 2.0中的表單驗證類的文件大小。我有一個包含文件輸入的表單,我想要做這樣的事情:CodeIgniter - 表單驗證和文件上傳數據

$this->form_validation->set_rule('file', 'File', 
       'file_type[image/jpeg|image/gif|image/png]|file_max_size[500]'); 

我想到了擴展驗證類以將其與上傳類結合起來,並根據上傳數據進行驗證,但可能費時。

有沒有人知道任何擴展的表單驗證類會做這樣的事情?

+2

我通常首先驗證表單,如果一切正常,我開始檢查文件上傳的有效性。 – janosrusiczki 2011-03-03 06:59:56

回答

10

文件上傳類實際上有它自己的一套驗證規則可以設置像這樣

$config['upload_path'] = './uploads/'; 
$config['allowed_types'] = 'gif|jpg|png'; 
$config['max_size'] = '100'; 
$config['max_width'] = '1024'; 
$config['max_height'] = '768'; 

$this->load->library('upload', $config); 

(taken from CI docs)

+0

如果該文件不符合驗證配置將更新表單驗證錯誤?例如,如果文件太大,validation_errors()函數是否會顯示一條錯誤消息,說明這一點? – ShoeLace1291 2011-03-04 07:02:59

+1

不,你必須單獨處理文件上傳錯誤,所以首先我會檢查輸入字段驗證,然後'do_upload()',並且有一個函數來顯示特定的上傳驗證錯誤。這些都在我的答案中鏈接到的文檔中。 – jondavidjohn 2011-03-04 13:22:12

+2

如果您將上傳字段添加到驗證中,但不給它任何驗證規則('$ this-> form_validation-> set_rules('file_to_upload','上傳文件','');'),那麼您可以把上傳錯誤消息放到form_validation對象中,它會自動正確顯示('$ this-> form_validation - > _ field_data ['file_to_upload'] ['error'] = $ this-> upload-> display_errors('','' );')。在$ this-> upload-> display_errors()中需要使用單引號,以去除通常由'display_errors()'添加的''''''''''''''''''''''''''''''''''''''''''''''''。 – 2012-09-07 22:58:39

9

我有同樣的問題。我建立了一個聯繫表格,允許用戶同時上傳頭像和編輯其他信息。表單驗證錯誤分別顯示在每個字段中。我無法承受文件輸入和其他文件輸入的不同顯示方案 - 我有一個標準的方法來處理顯示錯誤。

我使用了控制器定義的屬性和回調驗證函數來合併任何上傳錯誤和表單驗證。

這裏是我的代碼的摘錄:

# controller property 

private $custom_errors = array(); 

# form action controller method 

public function contact_save() 
{ 
    # file upload for contact avatar 

    $this->load->library('upload', array(
     'allowed_types'=>'gif|jpg|jpeg|png', 
     'max_size'=>'512' 
    )); 

    if(isset($_FILES['avatar']['size']) && $_FILES['avatar']['size']>0) 
    { 
     if($this->upload->do_upload('avatar')) 
     {   
      # avatar saving code here 

      # ... 
     } 
     else 
     { 
      # store any upload error for later retrieval 
      $this->custom_errors['avatar'] = $this->upload->display_errors('', ''); 
     } 
    } 

    $this->form_validation->set_rules(array(
     array(
      'field' => 'avatar', 
      'label' => 'avatar', 
      'rules' => 'callback_check_avatar_error' 
     ) 
     # other validations rules here 
    ); 

    # usual form validation here 

    if ($this->form_validation->run() == FALSE) 
    { 
     # display form with errors 
    } 
    else 
    { 
     # update and confirm 
    } 

} 

# the callback method that does the 'merge' 

public function check_avatar_error($str) 
{ 
    #unused $str 

    if(isset($this->custom_errors['avatar'])) 
    { 
     $this->form_validation->set_message('check_avatar_error', $this->custom_errors['avatar']); 
     return FALSE; 
    } 
    return TRUE; 
} 

注:因爲如果在其他表單字段的任何錯誤,在上傳成功的文件輸入不會重新填充,我存儲和更新它之前的任何其他驗證發生 - 所以用戶不需要重新選擇文件。如果發生這種情況,我的通知會有點不同。

+2

這是$ _FILES數組的好技巧。作爲您的方法的替代方案,我將文件數組檢查移入驗證回調中,以便我可以運行其他驗證。 – 2012-03-06 13:58:16