Thursday 7 July 2011

CodeIgniter: Resetting form validation

 

In one of my php projects I'm using CodeIgniter and its Form Validation library. I have validation rules defined in a config file located at:

system\application\config\form_validation.php

Sample rules definition for action "item/add" could look as follows:
$config = array(
'item/add' => array(
array(
'field' => 'name',
'label' => 'lang:name',
'rules' => 'trim|xss_clean|required|max_length[50]'
),
array(
'field' => 'type',
'label' => 'lang:type',
'rules' => 'trim|xss_clean|required|callback_type_check'
)
),
(...)
As you can see I'm using both built-int and custom rules (callback_type_check).

This works fine with my 'Add Item' form.

However, I wanted to reuse the validation logic at other place, where the user can provide multiple items to add at once in a file where each row represents a single item. So I read line by line from the file and want to validate each line. To do that I reset values in $_POST array and perform validation:
$_POST["name"] = $nameReadFromFile;
$_POST["type"] = $typeReadFromFile;
if ($this->form_validation->run('item/add') == FALSE) {
// handle validation error for current item
}
The problem is that when validation fails for one item then the error is persisted and all following invocations will fail as well, even if items are valid.

So, I added a reset function to my controller that resets Form Validation library:
function _reset_validation()
{
// Store current rules
$rules = $this->form_validation->_config_rules;

// Create new validation object
$this->form_validation = new CI_Form_validation();

// Reset rules
$this->form_validation->_config_rules = $rules;
}
The function simply remembers the rules that were loaded from config file when validation object was created, creates a new validation object and resets the rules. I call it after each row is validated.

1 comment:

Саня said...

Why do you keep the rules?