Search code examples
phpformscodeignitervalidation

CodeIgniter Form Validation. Multiple calls not working


I am using CodeIgniter. I have been trying to debug a non-working script.

I have come to the conclusion that when utilizing $this->form_validation->run(); (the form validation class), after the first named call, e.g $this->form_validation->run(form_1);, all following calls return true.

I am developing a multi step form and when $this->form_validation->run(form_1); correctly returns true, $this->form_validation->run(form_2); incorrectly returns true.

Anyone have any clue as to why? Can multiple calls not be held in a single function within a controller or is there a special approach? Cheers


Solution

  • the way codeigniter is setup doesn't lend itself to allow you to validate with multiple rules, you can extend the form helper with a function to group rules (http://ellislab.com/codeigniter/forums/viewthread/120221) or like I did in my application/config/form_validation.php I simply combined multiple groups into its own set of rules and referred to the single rule of combined rules.

    <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    $config = array(
    
      "campaign" => array(
        array(
          "field" => "campaign[title]",
          "label" => "campaign title",
          "rules" => "trim|required|max_length[255]|xss_clean"
        )
      ),
    
      "user" => array(
        array(
          "field" => "user_info[email]",
          "label" => "email",
          "rules" => "trim|required|valid_email|is_unique[user_info.email]|max_length[255]|xss_clean"
        )
      )
    );
    
    $config["campaign_user"] = array_merge($config['campaign'], $config['user']);
    

    The line of interest is the last one, where the two rules are combined:

    $config["campaign_user"] = array_merge($config['campaign'], $config['user']);

    and in your controller you would just call the single rule:

    if($this->form_validation->run('campaign_user'))
    {
        # validation successful
    }