[eluser]diez[/eluser]
Recently I've had the need to add custom form errors while using the form validation class. I know I can create a callback function within the set_rule() method. However, during certain situations this caused me to make duplicate database calls.
Here's how you would use the add_custom_error() function:
Controller
Code:
$this->load->library('form_validation');
if ($this->input->post('email') != $user_email_from_database)
{
$this->form_validation->add_custom_error('email_field', "The email entered is not registered as an account.");
}
if ($this->form_validation->run() == FALSE)
{
$this->load->view('login/login_view');
}
View
Code:
<html>
.......
<?php echo validation_errors(); ?> <!-- will display both native and custom errors-->
<h1>New User</h1>
<?php echo form_open('login'); ?>
<h5>Email Address</h5>
<?php echo form_error('email'); ?> <!-- will display both native and custom errors-->
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
.......
<div><input type="submit" value="Submit" /></div>
</form>
.......
</html>
NOTE:
There are 2 ways of outputting the errors.
you can use:
Code:
1.) echo form_error('email'); <!-- will display individual error msg associated with the form field -->
2.) echo validation_errors(); <!-- will display all form error msgs as a batch -->
native errors will be displayed first (if there are any) then, custom errors will be displayed in second priority.
If you want to use the add_custom_error() function extending the form validation class in CI, you can implement the following:
1.) Download the MY_Form_validation.php attachment and save it in your application/library folder
The only code added in the extended class is the following:
Code:
//***class variable we define at the top of our extended class
var $custom_field_errors = array(); //array that hold fields from errors
//***new function
function add_custom_error($field = '', $error_message = '')
{
if($field == '')
{
return '';
}
$this->custom_field_errors[$field] = $error_message;
return true;
}
//***code snippet that is added into the run() method that we extend
//insert custom errors into native form validation error arrays
if(count($this->custom_field_errors) > 0)
{
foreach($this->custom_field_errors as $field => $error_message)
{
$this->_error_array[$field] = $error_message;
$this->_field_data[$field]['error'] = $error_message;
}
}