
This is a quick tip if your’re looking for a “required_if” rule in CodeIgniter. Basically the rule is as follows: Make form field-A required if form field-B is filled in. The most common case scenario is changing a password, where the original password is required first, but is conditional only if a new password is entered.

If your form validation rules are defined on runtime you can simply modify your rules during processing as such:
$required_if = $this->input->post('password') ? '|required' : '' ;
$this->form_validation->set_rules('current_password', 'current password', 'trim'. $required_if .'|min_length[6]');
$this->form_validation->set_rules('password', 'password', 'trim|min_length[6]|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', 'password confirmation', 'trim');

heya! thanks for this. worked like a charm.
Good tip, works great. Thanks.
Hi,
see the codeigniter validation library on tahsin’s garage
I’ve encountered a problem while trying to confirm a password as you did above: When there’s a mismatch between password and confirm, it says “The Password field does not match the password_confirm field”, instead of “The Password field does not match the password confirmation field”.
@John, the second param in
set_rules()is the pretty label, make sure that is set properly.$this->form_validation->set_rules('password_confirm', 'password confirmation', 'trim');I thought I would post this here. Perhaps others might find it useful. I developed this form validation library as an attempt to try to somewhat replicate Perl’s DataFormValidator module.
Code Igniter Form Validate
Please leave comments on the Github page rather then here.