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(As you can see I'm using both built-int and custom rules (callback_type_check).
'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'
)
),
(...)
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;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.
$_POST["type"] = $typeReadFromFile;
if ($this->form_validation->run('item/add') == FALSE) {
// handle validation error for current item
}
So, I added a reset function to my controller that resets Form Validation library:
function _reset_validation()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.
{
// 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;
}
1 comment:
Why do you keep the rules?
Post a Comment