Search code examples
codeigniter-3codeigniter-form-validation

Codeigniter Form validation: Stop validating following rules if a rule fails


This is my controller method to process the user input

function do_something_cool()
{
  if ($this->form_validation->run() === TRUE)
  {
    // validation passed process the input and do_somthing_cool
  }
  // show the view file
  $this->load->view('view_file');

Validation Rules are as follow:

<?php

$config = array(

  'controller/do_something_cool' => array(
    array(
      'field' => 'email',
      'label' => 'Email',
      'rules' => 'trim|required|valid_email|callback_check_email_exists',
     )
   )
 );

My problem: If the user input is not a valid email, the validation rule is not stopping from executing the next rule, that is callback function in this case. Therefore, even if the email is not valid, I am getting the error message for check_email_exists() callback.

Is there any option in CI to stop checking the other rules if a rule failed?


Solution

  • From system/libraries/Form_validation.php's _prepare_rules() method,

    "Callbacks" are given the highest priority (always called), followed by 'required' (called if callbacks didn't fail), and then every next rule depends on the previous one passing.

    That means, the input will be validated against the callbacks first. So we will have to check the input within the callback function itself.

    For the above case, I have modified my callback function as follows

    function check_email_exists($email)
    {
       if ($this->form_validation->valid_email($email) === FALSE)
       {
            $this->form_validation->set_message('check_email_exists', 'Enter a valid email');
            return FALSE;
        }
        // check if email_exists in the database
        // if FALSE, set validation message and return FALSE
        // else return TRUE
    }