CodeIgniter Form Validation — Conditional Required Field

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.

Change Password

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');
Bookmark and Share

Related posts

  1. CodeIgniter htaccess
  2. Saving Form Data to Google Spreadsheets Using PHP and the Google Docs API

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Previous post:

Next post: