CodeIgniter Forums
Validation depending on multiple fields? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Validation depending on multiple fields? (/showthread.php?tid=11883)



Validation depending on multiple fields? - El Forum - 09-26-2008

[eluser]fernando_nf[/eluser]
Hello,

Is it possible at all to validate a field (using the validation library) based on the value of other fields? For example, there are two text fields (form_input), and I want either of them or both to be non empty. However, the validation callback only gives you the value of a single parameter, so I can't check if the other field is filled or not.

I took a look at the source code of the Validation class, but couldn't find anything useful. I guess I could use $_POST directly, but that would be ugly. Can anyone shed some light on this?


TIA,


Validation depending on multiple fields? - El Forum - 09-26-2008

[eluser]onejaguar[/eluser]
I just write a custom callback that checks both fields. It does use $_POST directly but I don't see anything ugly about that.

Code:
function double_check($var)
{
  return ! (empty($var) && empty($_POST['other_field']))
}



Validation depending on multiple fields? - El Forum - 09-26-2008

[eluser]fernando_nf[/eluser]
Wouldn't prep'ing mess things up, though?


Validation depending on multiple fields? - El Forum - 09-26-2008

[eluser]onejaguar[/eluser]
Prepping does make it a little trickier; the result depends on which version of CI you are using.

In CI 1.6.x prep function change the $_POST values as they are called. For instance if your rules are:

Code:
$this->validation->set_rules('other_field','trim');
$this->validation->set_rules('field2','trim|callback_double_check');

Both values will be trimmed and stored in $_POST by the time double_check is called.

There is a new form validation library in CI 1.7.0 (not officially released yet) and it doesn't change $_POST until all rules and prep function have been run, so $_POST['other_field'] would not be trimmed when double_check was called. If you wanted access to the prepped variable you would use set_value(); e.g.:

Code:
return ! (empty($var) && empty($this->form_validation->set_value('other_field')))

Despite the function name set_value actually GETS the value. 1.7.0 is subject to change...


Validation depending on multiple fields? - El Forum - 09-29-2008

[eluser]fernando_nf[/eluser]
I see, thank you.