Welcome Guest, Not a member yet? Register   Sign In
introducing the form_validation->reset_validation() function
#1

[eluser]jmadsen[/eluser]
Just wasted 20 minutes being dumb, so thought I'd share & explain so you can spot this more easily if you run into it :-P

I have a page & I wanted to validate a certain part of the form, but then conditionally validate other parts. So, as I typically do, I made a _validate_part_1(), _validate_part_2(), etc

Each _validate_part_x() sets different rules; ie, first_name, last_name; then company_name; then password stuff, etc. Each _validate_part_x() then runs ->run() and returns true/false

This is perfectly fine, EXCEPT!

You are using the same instance of the form_validation library, and so it is hanging on to the rules you set earlier. So, each time you call form_validation->run(), you are checking ALL the rules you have set up until now. So, first_name will get checked even when it isn't in that particular _validate_part_x() function - 3 times in our example.

Now, normally this isn't an issue, but in my case, in the 2nd of 3 funcs I had a callback and for some reason it was fine in its "real" check & passing, but then failing afterwards and so producing the error on the page - and driving me #$%& nuts

The solution is to use the undocumented form_validation->reset_validation() at the top of each of your _validate_part_x() functions, which does as its name says and clears all the data from the previous ->run()

EDIT: that will reset your field data

Code:
$this->_field_data = array();

in my case it doesn't matter, but just realized and thought I'd better point that out. A MY_Form_validation method to clear rules might be the best solution

Hope that saves somebody a headache someday
#2

[eluser]skunkbad[/eluser]
reset_validation() is a CodeIgniter 3.X method. User's of the 2.1-stable branch will need to put their own implementation of a reset method into a MY_Form_validation.php. I did this a while back, and my method is similar to the CodeIgniter version, but is better because it allows for the config to be reset.

Code:
/**
* Reset the class so we can run form validation again
*/
public function reset($rules = array())
{
$this->_field_data = array();
$this->_config_rules = array();
$this->_error_array = array();
$this->_error_messages = array();
$this->_error_prefix = '<p>';
$this->_error_suffix = '</p>';
$this->error_string = '';
$this->_safe_form_data = FALSE;

// Validation rules can be stored in a config file.
$this->_config_rules = $rules;

log_message('debug', "Form Validation Class Reset");
}

// --------------------------------------------------------------
#3

[eluser]jmadsen[/eluser]
ah! thanks for pointing that out - forgot I was using v3

hmmmm...feels like a blog post coming on ;-)




Theme © iAndrew 2016 - Forum software by © MyBB