«

»

Codeigniter validation ( This field or that field, but not both )

Codeigniter’s validation class is awesome, but I ran into a situation where I wanted to set a rule that said something like:

Either Field A or Field B needs to be filled out, but not neither, and not both.
To do this I used PHP and popped a custom error on the form_falidation error array.

See below

// Codeigniter doesn't have a rule to say "this field or that field"
// So I'm making my own here, but passing the results back to codeigniter
// So it can display the errors uniformily to the view.
if( ($this->input->post('usergroups') || $this->input->post('systemgroups') )
&& !($this->input->post('usergroups') && $this->input->post('systemgroups')))
{
//Could do something here
}else{
$error='A group must be selected. Only one group can be selected at a time.';
$this->form_validation->_error_array['custom_error'] = $error;
}//end if

Permanent link to this article: http://www.lukemacneil.com/2009/11/06/codeigniter-validation-this-field-or-that-field-but-not-both/

Leave a Reply

Your email address will not be published.

You may 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>