Codeigniter Form Validation Callback checking multiple fields Codeigniter Form Validation Callback checking multiple fields codeigniter codeigniter

Codeigniter Form Validation Callback checking multiple fields


Use this in your controller to set your validation rules.

$this->form_validation->set_rules('username', 'Username', 'required');$this->form_validation->set_rules('password', 'Password', 'required|callback_terminal_login_check');

And a callback something like this. I'd use a model if you are comparing your post data to a database.

function terminal_login_check() {  $username = $this->input->post('username');  $password = $this->input->post('password');  // LOAD MODEL HERE  if ($this->authentication->DoTerminalAuthentication($username, $password))   {    echo $username;    return TRUE;  }   else   {    $this->form_validation->set_message('terminal_login_check', 'Invalid');    return FALSE;  }}

Edit 2013-07-09: Added required field to password validation rule so you don't have to hit the DB if someone doesn't add a password.


As I understand it, form validation works on a field by field basis. To achieve what you want, I would attach the callback to one of the fields (probably the password field would be best) and then access the other form field data using the global POST array. This way you don't need to pass anything to the callback function as parameters.


I prefer to use form validation for simple input validation like checking for empty fields, invalid email addresses, too short passwords etc. I tend not to use form validation for more complex logic like authentication. I'd put the authentication check in the action method rather than in a validation callback function. It would get past your particular problem by side-stepping it.

function terminal() {    $this->form_validation->set_rules('username', 'Username', 'required');    $this->form_validation->set_rules('password', 'password', 'required');       if ($this->form_validation->run())     {        $username = $this->input->post('username');        $password = $this->input->post('password');        if ($this->authentication->DoTerminalAuthentication($username, $password))        {            // Handle successful login        }        else        {            // Authentication failed. Alert the view.            $this->load->view('terminal', array('login_failed' => true));        }    }     else     {        $this->load->view('terminal', array('login_failed' => false));    }}

And then in the view you can place this below your login form

<?php if ($login_failed) : ?>    <span id="login-failed-message">Login failed</span><?php endif; ?>