Regular Expression Rules in Form Validation for Ext.CodeIgniter

Yes, I have a problem with CodeIgniter built-in Form Validation Library, the lack of direct Regular Expression test/rule is a huge turn off for me especially when I need to use Regular Expression to as a rule to verify user input.

There are alternative with the use of “callback” to by creating an additional method inside your Controller. The solution is good if you have a complex filtering but why bother when all you need to do is a simple RegExp verification. Based on my Twitter status:


status-5310657643

Based from a reply to the status.

reply

I took the challenge of extending Form Validation Library to add support for Regular Expression test. As a result here MY_Form_validation.php. The changes was minimal but since I need to tweak some of the existing method to allow the special character such as | and [ ] to be use in our Regular Expression the LOC for this modify is quite big.

Now you can add rule such as:

$this->form_validation->set_rules(
    'username',
    'Username',
    'trim|required|expression:/^([a-zA-Z0-9\.\-\_\|]{1,50})$/|xss_clean'
);

As you can see, an additional rule has been set with expression:/^([a-zA-Z0-9\.\-\_\|]{1,50})$/. With this new rule you can safely reject request such as below (with proper error message).

error

Posted in Code Snippet, CodeIgniter, Ext.CodeIgniter, How-To, Regular Expression | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>