Welcome Guest, Not a member yet? Register   Sign In
form-validation depending on a checkbox
#1

[eluser]sl3dg3hamm3r[/eluser]
hey there

I'm stuck with a common problem, I guess...

I have a form, where a user needs to select from certain drop-downs. Nothing fancy so far, simple form-validation.
Additionally, I have a checkbox, from which further form-validation would depend. E.g. "alternative delivery address" - if checked, the following fields are mandatory, if not, then not.

I couldn't come up with a smart solution so far. The only thing I can think of is for each address-field (name, street, city...) to define a callback. In each callback, I would check if the checkbox is marked, and then do the rest of the check.
This would result in many small callbacks, not so nice I'd say... could somebody think of a smarter solution?

Thx for any tipps!
Oliver
#2

[eluser]Haloperidol[/eluser]
maybe:

Code:
...
   // all the validations you want to run by default
   $this->form_validation->set_rules('email', 'E-mail', 'trim|required|valid_email');

   if (isset($this->input->post('checkbox_name')) && $this->input->post('checkbox_name') == 'on')
   {
      $this->form_validation->set_rules('other_variables', 'blablabla', 'trim|required');
   }

   if ($this->form_validation->run() === TRUE) {
...
#3

[eluser]sl3dg3hamm3r[/eluser]
I do store the rules in rule-groups in an external file, therefore I call them like

Code:
if ($this->form_validation->run('signup') == FALSE) { ...

Unfortunately, I can't chain/cascade different groups according to the manual I think, which would come real handy in here. Would be nice as an additional feature...
#4

[eluser]Haloperidol[/eluser]
then maybe
Code:
if (isset($this->input->post('checkbox_name')) && $this->input->post('checkbox_name') == 'on')
   {
      if ($this->form_validation->run('validation_if_checkbox_is_off') == FALSE || $this->form_validation->run('rest_of_validation_if_checkbox_is_on') == FALSE)
      {
         ...
      }
   } else {
      if ($this->form_validation->run('validation_if_checkbox_is_off') == FALSE)
      {
         ...
      }
   }

?
#5

[eluser]sl3dg3hamm3r[/eluser]
yeah, this would work. it results in redundant rules in the external file, though. But might be still better than many small callbacks, I guess...
#6

[eluser]PeterGreffen[/eluser]
Here's a good solution from Mike Ryan and davidbehler: http://ellislab.com/forums/viewthread/96050/




Theme © iAndrew 2016 - Forum software by © MyBB