Welcome Guest, Not a member yet? Register   Sign In
Validation depending on multiple fields?
#1

[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,
#2

[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']))
}
#3

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

[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...
#5

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




Theme © iAndrew 2016 - Forum software by © MyBB