2011-03-04 28 views

回答

2

不修改CodeIgniter的表單驗證類(CI_Form_validation),有沒有辦法從一個配置文件中加載驗證規則和使用規則集的方法。由於表單驗證碼目前經營,如果沒有規則已經另有規定

可以擴展表單驗證類,並得到這個工作,但是,相對簡單的配置文件規則只檢查。創建一個名爲MY_Form_validation.php文件,並把它應用/核心/目錄。

class MY_Form_validation extends CI_Form_validation { 
    // You only need to change the run() method, so we'll define a (modified) version. 
    // This will override the existing run() method so that it uses rules set from 
    // set_rules() AND from the config file. 
    function run($group = '') 
{ 
    if (count($_POST) == 0) 
    { 
     return FALSE; 
    } 

      // If there are any configuration rules defined, go ahead and use them 
    if (count($this->_config_rules) != 0) 
    { 
     // 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]); 
     } 
     else 
     { 
      $this->set_rules($this->_config_rules); 
     } 
    } 

    // Load the language file containing error messages 
    $this->CI->lang->load('form_validation'); 

    // Cycle through the rules for each field, match the 
    // corresponding $_POST item and test for errors 
    foreach ($this->_field_data as $field => $row) 
    { 
     // Fetch the data from the corresponding $_POST array and cache it in the _field_data array. 
     // Depending on whether the field name is an array or a string will determine where we get it from. 

     if ($row['is_array'] == TRUE) 
     { 
      $this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']); 
     } 
     else 
     { 
      if (isset($_POST[$field]) AND $_POST[$field] != "") 
      { 
       $this->_field_data[$field]['postdata'] = $_POST[$field]; 
      } 
     } 

     $this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']); 
    } 

    // Did we end up with any errors? 
    $total_errors = count($this->_error_array); 

    if ($total_errors > 0) 
    { 
     $this->_safe_form_data = TRUE; 
    } 

    // Now we need to re-set the POST data with the new, processed data 
    $this->_reset_post_array(); 

    // No errors, validation passes! 
    if ($total_errors == 0) 
    { 
     return TRUE; 
    } 

    // Validation fails 
    return FALSE; 
} 

注意,我沒有在CodeIgniter安裝上測試過這個。但它應該工作。另外請注意,這是使用一個set_rules()方法定義的規則配置文件規則的優先級。