How to Set Form Validation Rules for CodeIgniter Dynamically?


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 this, or must I use the old form validation class that is deprecated now?

12/31/2011 8:26:40 AM

Accepted Answer

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


More info on:

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. :)

2/28/2009 2:17:01 PM

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');

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow