CodeIgniter Forums
Required form validation rule based on value of another field - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Required form validation rule based on value of another field (/showthread.php?tid=12471)



Required form validation rule based on value of another field - El Forum - 10-20-2008

[eluser]McNoggin[/eluser]
I am creating a form with a drop down list that allows the user to pick an existing value. If the value they want isn't in the list they can select 'Other' and will then be allowed to enter a new value into an input field.

Currently I have the validation rules setup to require both the dropdown value, and the new input value. I'd like to know if there is a way to configure the second field to only be required if a specific value in the other field is set.

To clear things up here is what the HTML looks like
Code:
<select name="choice_id">
  <option value="1">Choice 1</option>
  <option value="2">Choice 2</option>
  <option value="-1">Other</option>
</select>
&lt;input type="text" name="choice_name" /&gt;

In my controller I have these rules
Code:
$rules['choice_id']     = "required";
$rules['choice_name']     = "required";

However what I really want is way set it up so that 'choice_name' is only required if 'choice_id' is equal to -1.


Required form validation rule based on value of another field - El Forum - 10-20-2008

[eluser]Bramme[/eluser]
Sure, create a custom callback that checks the value of choice_id, if it's other, check if choice_name is ! empty...


Required form validation rule based on value of another field - El Forum - 10-20-2008

[eluser]McNoggin[/eluser]
I think I was making the problem harder then it really was. I started to use the call back when I realized the easiest way to do it.

Code:
$rules['choice_id']     = "required|integer";
if ($this->input->post('choide_id') == '-1') {
    // only require the name if the id is other
    $rules['choice_name']     = "required|alpha_dash";
}

Thanks for the help.


Required form validation rule based on value of another field - El Forum - 10-20-2008

[eluser]Bramme[/eluser]
That's an option too I guess, though I really think it'd be cleaner with your own callback...