• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Form Validation - Requiring one input OR the other

I'm new to CodeIgniter, but love it already. Was hoping to get a hand with some confusion with the form validation. Best as I can tell there is nothing about it specifically on this forum.

I have a form that collects city and state OR zip code. I can't for the life of me figure out how to validate this with CI. Obviously just using required for all three doesn't cut it since it's an OR situation. Best as I can tell a callback won't work either.

Am I just being ridiculous and not seeing the solution? If there is no way to check this with the validation library, how would I validate it myself and push the error message to the view?

Thanks in advance!

use an if statement to check if the fields are filled, before you build your requirements. As such:



$this->form_validation->set_error_delimiters('<p class="error">', '</p>');

if(empty($this->input->post('zipcode')) {
    $this->form_validation->set_rules('city', 'City', 'trim|required');
    $this->form_validation->set_rules('state', 'State', 'trim|required');

} else {

    $this->form_validation->set_rules('zip', 'Zip Code', 'trim|required');


if($this->form_validation->run()=== false) {
    // display errors
} else {
   //save form

Rules are set after the form is sent to the browser, so you still have access to $_POST vars from there in ($this->input->post(KEY); ). Hope that helps.

Wow! Duh...

That seems so obvious after having seen it. Definitely appreciate the direction!

Small note: empty() cannot check the return value of a function or method.

if (empty($this->input->post('zipcode'))) { ... }

You will get an error saying:

Quote:Fatal error: Can't use method return value in write context in ...

Corrected syntax will need to be:

$zipcode = $this->input->post('zipcode');
if (empty($zipcode)) { ... }

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.