Friday, June 11, 2010

codeigniter callback function to check valid username or email

this post are from here http://scottblaine.com/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:
1
2
$this->form_validation->set_rules( 'username', 'Username',
  'trim|required|callback_username_check' );
And then create a matching function like this:
1
2
3
4
5
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:
1
2
3
4
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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):
1
2
$this->form_validation->set_rules( 'username', 'Username',
  'trim|required|callback__username_check' );
Done!

No comments:

Post a Comment