Form Validation Callbacks Within CodeIgniter

There are many ways to add form validation within CodeIgniter. One way is by extending the form validation library with your own. Another way is by using callbacks. CodeIgniter support callbacks to form validation. I would like to show how callbacks can be added to the existing form validation set of rules.

Validation Rules

Here’s a typical form validation rule where the ‘url’ field is required.

$this->form_validation->set_rules(‘url’, ‘URL’,'required’ );

Validation Rules with Callbacks

This is how you add callbacks. Notice the ‘callback’ prefix.

$this->form_validation->set_rules(‘username’, ‘Username’, ‘callback_url_check’);

The Callback Function

The callback function. The ‘callback’ prefix is omitted.

function url_check() { 
  $regex = “your reg ex code here”;
  if(!preg_match($regex, $str)) {
    $this->form_validation->
    set_message(‘valid_url’, ‘Please enter a valid URL.);   return FALSE;
  } else {
    return TRUE;
  }
}

In the example above, you will need to supply your own regular expression to perform a url match. This is how you implement the callback function. It’s ideal for adding quick functions without extending the current CodeIgniter library.