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?
问题:
回答1:
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. :)
回答2:
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');
回答3:
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().