I had the same requirement for adding custom form validation error messages in codeigniter 2 (e.g. "You must agree to our Terms & Conditions"). Naturally it would be wrong to override the error messages for require and greater_than as it would erroneously produce messages for the rest of the form. I extended the CI_Form_validation class and have overridden the set_rules method to accept a new 'message' parameter:
<?php
class MY_Form_validation extends CI_Form_validation
{
private $_custom_field_errors = array();
public function _execute($row, $rules, $postdata = NULL, $cycles = 0)
{
// Execute the parent method from CI_Form_validation.
parent::_execute($row, $rules, $postdata, $cycles);
// Override any error messages for the current field.
if (isset($this->_error_array[$row['field']])
&& isset($this->_custom_field_errors[$row['field']]))
{
$message = str_replace(
'%s',
!empty($row['label']) ? $row['label'] : $row['field'],
$this->_custom_field_errors[$row['field']]);
$this->_error_array[$row['field']] = $message;
$this->_field_data[$row['field']]['error'] = $message;
}
}
public function set_rules($field, $label = '', $rules = '', $message = '')
{
$rules = parent::set_rules($field, $label, $rules);
if (!empty($message))
{
$this->_custom_field_errors[$field] = $message;
}
return $rules;
}
}
?>
With the above class you would produce your rule with a custom error message like so:
$this->form_validation->set_rules('business_id', 'Business', 'greater_than[0]', 'You must select a business');
You may also use '%s' in your custom message which will automatically fill in the label of fieldname.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…