I'm using CodeIgniter's form validation callback function, here is it:
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;
}
.. I'm using the above function for three form inputs:
$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']);
}
The problem appears, when I want to display a form validation error message with the following statement:
$this->form_validation->set_message($field . '_min', sprintf($this->lang->line('dev_s_invalid_rate'), strtolower($field)));
(in the callback function).
So: it should set a error message corresponding to the $field
data, so when the $field
is water
, it should set a error message for water_min
(as that is the validation rule field name).. but then I'm receiving following message:
Unable to access an error message corresponding to your field name.
.
I've created one callback function for three fields, just to prevent repeating same looking functions, which will have to check/work the same... unfortunately the errors corresponding to the each input can not be accessed.
change
$this->form_validation->set_message($field . '_min', sprintf($this->lang->line('dev_s_invalid_rate'), strtolower($field)));
to
$this->form_validation->set_message(_validate_rate, sprintf($this->lang->line('dev_s_invalid_rate'), strtolower($field)));
The error message corresponds to the function, not the field. That way your function can be generically used for multiple fields. In your error message you could write:
'The %s field is not correct'
and it will insert the field name into the %s