Basic Pattern Matching Form Validation in CodeIgniter
February 25th, 2010
CodeIgniter comes with an excellent Form Validation library right out of the box. This library features a number of validation and preparation functions that are executed on posted form fields when the run() method is called. If you need additional functionality, it is also very easy to add your own validation/preparation functions to your application, without modifying any of the underlying CodeIgniter codebase.
If you have a decent level of experience with Microsoft’s Excel, you may have had to develop a custom cell format from time to time. This basic format syntax provides a very loose, but functional, method of defining the format of the input you expect. In this tutorial, we’ll define a new form field validation rule (called matches_pattern) that excepts one argument that will define the pattern we want the user’s input to match. Our goal is to make something very simple to use, but moderately powerful, so we’re going to stay away from having to use regular expressions within our validation rules. Instead, we’ll create a set of replacement characters to use within our rules instead: # to represent a number, ? to represent an alphabetical character and ~ to represent any character.
These characters will allow us to validate a user’s input matches specific cases. For instance, phone numbers could be forced to match (###) ###-#### or a date field could be forced to match ##-##-#### (MM-DD-YYYY).
The first step in extending CodeIgniter’s Form Validation library is to create our own Form Validation class within our applications libraries/ directory. By default, the prefix for your own extending classes is MY_, so we’ll create libraries/MY_Form_validation.php and stub out the following code:
We've now extended the default Form Validation library and we have a function, called matches_pattern() that we can call from our set_rules() method. Let's start fleshing out this method and translating our characters into their regular expression equivalents:
We're now using str_replace() to translate our special characters into their regular expression equivalents. Finally, we run through preg_match() and return a boolean as to whether the user input ($str) matches. You may wonder why we're just not returning the value of preg_match(). Unfortunately, preg_match() returns a 1 or 0 (at least on my development server) and CodeIgniter expects an explicit boolean, therefore we run it through the conditional really quick.
Our last step is escaping some of the standard regular expression special characters. In regular expressions, characters like (, ), [ and many others have special meanings. We don't want to make use of these special meanings within our patterns though; if our patterns contains an ( we literally want to match on that character (rather than capturing a successful match). We'll implement this by modifying our character arrays and replacing these special characters with their escaped versions:
The final step in this process is to define the error message that is reported when our validation function returns FALSE. This is done by defining your own language file within your application at language/english/form_validation_lang.php. The content within this file will be appended to CodeIgniter default form_validation_lang.php file:
The %s within this language definition will be replaced by the field name in which you include this rule. To use our new rule, we just append it to the rule set for any of our fields within our controller:
It's very easy to create your own validation rules. If you find yourself writing callback functions to do the same things over and over, consider bringing that function out into your own Form Validation library. The matches_pattern() function we wrote here provides an easy-to-use, yet simple, way to match a specific pattern - just remember to inform your users of what that pattern is! If you wanted, you could an include another %s within your language definition that would insert the specific pattern in the error message.


February 25th, 2010 at 1:16 pm
Very cool Michael! I hate always having to copy my callbacks from project to project.
February 25th, 2010 at 1:18 pm
@Todd
Yeah, it’s definitely a pain in the ass. One of my favorite personal validation functions is is_unique, but you’ll have to wait for the CodeIgniter Cookbook for that one!
April 8th, 2010 at 12:31 pm
@Michael
I don’t know how you plan to implement the “is_unique” rule, but I have done this in the past. My way of doing it is to have the validation function take 2 param…the model name and the field name. Then I just have to have a “is_unique” function the specified model. The validation function then calls the is_unique function in the model and sends it the user input and the field name. The is_unique then chacks the database, and does its then, then returns TRUE or FALSE.
Here is how I use it:
$this->form_validation->set_rules(‘username’, ‘Username’, ‘trim|required|is_unique[user_model,username]‘);
Note: The actual function “is_unique” has a prototpye of “function is_unique($str, $params)” then I have to parse the $params variable out becasue of the way that the FormValidation library sends it.
If you would like to see the code let me know and I can shoot it over.
Dan
April 8th, 2010 at 12:53 pm
@Dan
My
is_unique()involves a lot less work, but nonetheless good job on being inventive and coming up with a solution that meets your needs!July 4th, 2010 at 9:17 pm
i have try your tutorial but somehow there is a problem with the lang file.
i need to name it my_form_validation_lang instead of form_validation_lang
thanks for the code…
nice sharing.
July 21st, 2010 at 1:29 am
Hello,
see how you can secure your website more with this extended My input libray for codeigniter here and also see the weakness of codeignite Input library on here. Thanks.