2012-05-06 105 views
1

我使用CodeIgniter的表單驗證回調函數,在這裏驗證函數是:一個多輸入

function _validate_rate($input, $field) 
{ 

    if (!in_array($field, array("water", "earth", "fire"))) 
    { 
     return FALSE; 
    } 

    $min = (int) $this->input->post($field . '_max'); 
    if ($min > 0 AND $min < $input) 
    { 
     $this->form_validation->set_message($field . '_min', sprintf($this->lang->line('dev_s_invalid_rate'), strtolower($field))); 
     return FALSE; 
    } 
    return TRUE; 
} 

..我用了三個表單輸入上面的功能:

$form_rules = array(
    'water_min' => array (
     'field' => substr($this->lang->line('dev_field_water'), 0, -1), 
     'rules' => 'trim|xss_clean|max_length[4]|numeric|callback__validate_rate[water]' 
    ), 
    'earth_min' => array (
     'field' => substr($this->lang->line('dev_field_earth'), 0, -1), 
     'rules' => 'trim|xss_clean|max_length[4]|numeric|callback__validate_rate[earth]' 
    ), 
    'fire_min' => array (
     'field' => substr($this->lang->line('dev_field_fire'), 0, -1), 
     'rules' => 'trim|xss_clean|max_length[4]|numeric|callback__validate_rate[fire]' 
    ) 
); 
foreach($form_rules as $input => $data) 
{ 
    $this->form_validation->set_rules($input, $data['field'], $data['rules']); 
} 

出現的問題是,當我想以顯示與下面的語句形式驗證錯誤消息:

$this->form_validation->set_message($field . '_min', sprintf($this->lang->line('dev_s_invalid_rate'), strtolower($field))); 

(在回調函數中)。

所以:它應該設置一個錯誤信息對應$field數據,所以當$fieldwater,它應該water_min設置一個錯誤信息(因爲這是驗證規則字段名)..但隨後我收到以下消息:

Unable to access an error message corresponding to your field name.

我爲三個字段創建了一個回調函數,只是爲了防止重複相同的功能,這將不得不檢查/工作相同...不幸的是,每個輸入對應的錯誤無法訪問。

回答

1

變化

$this->form_validation->set_message($field . '_min', sprintf($this->lang->line('dev_s_invalid_rate'), strtolower($field))); 

$this->form_validation->set_message(_validate_rate, sprintf($this->lang->line('dev_s_invalid_rate'), strtolower($field))); 

該錯誤消息對應於該函數,而不是字段。這樣你的功能就可以一般用於多個領域。在您的錯誤信息,你可以寫:

'The %s field is not correct' 

,它會插入字段名到%S