Ulyssesonline

the tech surfer

  • Home
  • About
  • Archives
You are here: Home / General / Form Validation Callbacks Within CodeIgniter

February 28, 2011

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’ );

$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’);

$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;
  }
}

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.

Filed Under: General, PHP Tagged With: callback, codeigniter, form validation, library, PHP

Comments

  1. Weverton says

    October 11, 2011 at 12:36 pm

    Is it possible put the callback function ‘url_checker’ in a helper? If not, where can I put it except in the controller?

  2. Ulysses says

    October 11, 2011 at 8:42 pm

    I’m not sure if you can extend a helper. I’ve only done it via the main CI controller. Here’s a good article covering that.

  3. Weverton says

    October 12, 2011 at 4:24 am

    Hello Ulysses, I’ve made test here and a helper function isn’t visible for the callback_function_name.

    To resolve this problem I’ve have create a MY_Form_validation Library, which extends CI_Form_validation and the callback_functions go to there. So, this resolve my problem =)

    Thank you for your answer!

  4. Ulysses says

    October 13, 2011 at 9:54 pm

    Great. I did the same for an earlier project.

Copyright © 2003 - 2018