2

CodeIgniter Form Validation — Conditional Required Field

CodeIgniter conditional required fields

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

Related posts

  1. CodeIgniter NGINX Rewrite Rules
  2. CodeIgniter htaccess

{ 2 comments… read them below or add one }

David June 12, 2010 at 7:23 am

heya! thanks for this. worked like a charm.

Nextra September 1, 2010 at 6:34 am

Good tip, works great. Thanks.

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: