2012-06-20 52 views
0

我正在使用帶有codeigniter的模塊化MVC。我有一個模塊播放列表,其中我有一個管理控制器,並且我有一個私有$規則變量用於設置表單驗證規則。codeigniter中的編輯表單的有限驗證

我在同一個文件中創建和編輯函數,並驗證兩個表單(添加,編輯也是從一個文件form.php動態創建的)。

$this->load->library('form_validation'); 
$this->form_validation->set_rules($this->rules); 
$this->form_validation->set_error_delimiters(' <p class="error">', '</p>'); 

這些用於創建和編輯功能。一些我不想在編輯模式下驗證的字段。我是否需要爲它們創建不同的私有規則,或者是否有更好的方法來處理codeigniter,因爲我對它很陌生。我想刪除FILE標籤的驗證,因爲用戶不需要在編輯模式下上載。

感謝

+0

使用標誌變量,看狀態,如果它被夾然後設置各個領域mendatory其他明智的如果更新那麼一些應該是可選的 –

回答

1

下面是從CI論壇(original link)的答案。

您可以使用某種形式的heirachy定義創建/編輯規則,然後;

<?php 
$this->form_validation->set_group_rules('createModule'); 
$this->form_validation->set_group_rules('editModule'); 
if($this->form_validation->run() == FALSE) { 
    // whatevere you want 
} 
?> 

或者,你可以這樣做;

<?php 
// This will validate the 'accidentForm' first 
$this->form_validation->set_group_rules('createModule'); 
if($this->form_validation->run() == FALSE) { 
    // whatevere you want 
} 
// Now we add the 'locationForm' group of rules 
$this->form_validation->set_group_rules('editModule'); 
// And now we validate *both* sets of rules (remember that the createModule rules are still 
// there), but it doesn't necessarily matter, since it will simply redo the 'createModule' 
// validation while also doing the 'editModule' validation 
if($this->form_validation->run() == FALSE) { 
    // whatevere you want 
} 
?> 

下面是擴展Form_validation類的代碼,保存在應用程序庫文件夾MY_Form_validation.php

<?php 
class MY_Form_validation extends CI_Form_validation { 

    /** 
    * Set Rules from a Group 
    * 
    * The default CodeIgniter Form validation class doesn't allow you to 
    * explicitely add rules based upon those stored in the config file. This 
    * function allows you to do just that. 
    * 
    * @param string $group 
    */ 
    public function set_group_rules($group = '') { 
     // Is there a validation rule for the particular URI being accessed? 
     $uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group; 

     if ($uri != '' AND isset($this->_config_rules[$uri])) { 
      $this->set_rules($this->_config_rules[$uri]); 
      return true; 
     } 
     return false; 
    } 

} 

?>