Clearing CodeIgniter Form Validation Rules
We recently had a case where we created a huge form that had separate sections that we needed to validate, we call them “modules”. Our goal was to send all the form data to a single save function, and then that function could call each form validation function for the included modules. We ran into a small problem with Code Igniter running multiple form validation functions; more specifically, if the first form validation function gave an error, that error would not be cleared in the second form validation function and so on. This meant that all our validation scripts would “carry over” their errors, which is no good.
Our fix was to clear all the variables used in the Code Igniter Form Validation Class, which basically sends it back to an empty state. Here is an example:
<?php
//we POST to this function from our form
function save() {
$modules = array(
'patient_info',
'patient_history'
);
$this->load->library('form_validation');
$errors = array();
foreach($modules as $module) {
$function = 'save_'.$module;
$errors = $this->$function();
//reset form validation class
$this->form_validation->_field_data = array();
$this->form_validation->_config_rules = array();
$this->form_validation->_error_array = array();
$this->form_validation->_error_messages = array();
$this->form_validation->error_string = '';
}
//do checks on $error array, return or echo accordingly
}
function save_patient_info() {
$this->form_validation->set_rules('first_name','First Name','required|xss_clean|max_length[300]');
$this->form_validation->set_rules('email','Email Address','required|xss_clean|max_length[300]|valid_email');
if ($this->form_validation->run() != FALSE) {
//do work
return TRUE;
} else {
return validation_errors();
}
}
function save_patient_history() {
$this->form_validation->set_rules('last_visit_date','Last Visit Date','required');
$this->form_validation->set_rules('tetanus_shot','Tetanu Shot in past 5 years','required');
if ($this->form_validation->run() != FALSE) {
//do work
return TRUE;
} else {
return validation_errors();
}
}
?>
Remember that your global $_POST variable will remain set throughout the entirety of the all the function calls, so each function will validate against it, as it should. This saves you from having to making a massive validation function, which may break if a particular module wasn’t included on the form. This was an easy way we found, if you have a better one, we would love to hear about it!
Comments