views:

1743

answers:

2

With the new version of CodeIgniter you can only set rules in a static form_validation.php file. I need to analyze the posted info, i.e, only if they select a checkbox, only then do I want certain fields to be validated.

What's the best way to do that? Or do I must use the old form validation class (which is deprecated now)

+1  A: 

You could write your own function which checks whether said checkbox is selected, and applies the validation manually.

function checkbox_selected($content) {
    if (isset($_REQUEST['checkbox'])) {
        return valid_email($content);
    }
}

$this->form_validation->set_rules('email', 'Email', 'callback_checkbox_selected');
Samir Talwar
+2  A: 

You cannot only set rules in the config/form_validation.php file. You can also set them with:

   $this->form_validation->set_rules();

More info on: http://codeigniter.com/user_guide/libraries/form_validation.html#validationrules

However, the order of preference that CI has, is to first check if there are rules set with set_rules(), if not, see if there are rules defined in the config file.

So, if you have added rules in the config file, but you make a call to set_rules() in the action, the config rules will never be reached.

Knowing that, for conditional validations, I would have a specific method in a model that initializes the form_validation object depending on the input (for that particular action). The typical situation where I've had the need to do this, is on validating shipping and billing addresses (are they the same or different).

Hope that helps. :)

Favio