Form validation callbacks and private functions

If you’re familiar with CodeIgniter you probably know about callbacks within form validation. Callbacks allow you to do your own validation of fields. For example, if you want to verify if a username is unique then you could create a username_check function to validate the field. You add the callback rule like this:

$this->form_validation->set_rules( 'username', 'Username',
  'trim|required|callback_username_check' );

And then create a matching function like this:

function username_check( $username )
{
  // some code
}
?>

However, as this is currently implemented someone could access your function as a page at a URL like example.com/index.php/login/username_check/ if they guessed the function name. While that may not have any ill side-effects, it’s probably just as well if no one can access the function besides you.

In come private functions for controllers, which allow you to create a function like this:

function _utility()
{
  // some code
}

And if you try to access the function via a URL, like example.com/index.php/login/_utility/, you’ll get a 404 (page not found).

You probably see where I’m going with this. If you create your callbacks as private functions, no one will be able to access the callbacks as pages. It’s quite simple to do. You add an underscore before your callback function name:

function _username_check( $username )
{
  $valid_username = TRUE; // You would perform some kind of check on the field here

  if ($valid_username == FALSE)
  {
    $this->form_validation->set_message('_username_check', 'The username you have provided is not valid.');
    return FALSE;
  }
  else
  {
    return TRUE;
  }
}

And then add an underscore in your callback rule (note the two underscores after callback):

$this->form_validation->set_rules( 'username', 'Username',
  'trim|required|callback__username_check' );

Done!

,

5 Responses to “Form validation callbacks and private functions”

  1. Eric Jones July 30, 2009 at 4:18 pm #

    From a newbie to Codeigniter, thanks for the hint. I read the user guide, but never put those two together.

    • Scott July 30, 2009 at 4:41 pm #

      You bet! Glad you found it useful.

  2. ph1047 August 17, 2009 at 4:30 pm #

    it is NOT working. Tested on 1.7.1.

    $this->form_validation->set_rules(‘login’, ‘Login’, ‘trim|required|min_length[4]|max_length[24]|callback__usr_exists’);

    function _usr_exists($str)

    i get
    “Unable to access an error message corresponding to your field name.”

  3. ph1047 August 17, 2009 at 4:34 pm #

    Ah damn. I forgot to change this…..
    $this->form_validation->set_message(‘_usr_exists’, ‘gtfo’);
    It works OK…

  4. Scott August 17, 2009 at 11:18 pm #

    I didn’t originally dive much into the intricacies of setting up private functions. I’ve since updated my example to note that you need to specify the message for the field if it fails. Thanks for the feedback!