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.
Is it possible put the callback function ‘url_checker’ in a helper? If not, where can I put it except in the controller?
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.
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!
Great. I did the same for an earlier project.