Ali
Ali

Reputation: 267049

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?

Upvotes: 0

Views: 13243

Answers (3)

user2067021
user2067021

Reputation: 4529

If you want to avoid writing your own validation function, I came across this site which suggests that, if you're dynamically setting your rules using the Form Validation class, you can simply build up the rule string argument to set_rules() dynamically.

You first test the POST data to determine if your condition is satisfied (eg. checkbox selected) and then, as necessary, add a "|required" to the rule string you pass to set_rules().

Upvotes: 0

Favio
Favio

Reputation: 1009

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

Upvotes: 5

Samir Talwar
Samir Talwar

Reputation: 14330

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

Upvotes: 3

Related Questions