Extending CodeIgniter’s Validation Library To Check For Unique Values

Updated August 29, 2010: I’ve updated this post to be compatible with the latest version of CodeIgniter. It’s currently compatible with 1.7.0 and later. If you are still running on an older version and want the old version of this code to match let me know; I will send it to you. When I updated the post I also reset the discussion since most of it was specific to the old code.

February 15, 2011 Calvin Froedge rightly notes in the comments that with the release of CodeIgniter 2.0 the old PHP-4-compatible constructor style no longer works. The code below is updated to reflect that. He also has some thoughts about internationalization with language files and storing the visitor’s language in the session variables. This should be back-compatible with old versions CodeIgniter as long as you’re running PHP 5 on your server.

I’m working on small web application and I’m building it with CodeIgniter. Like most web applications, mine requires user registration and login. And like most login systems, mine is happiest if each user has a unique username. While the CodeIgniter validation library is pretty robust, it doesn’t come with a function for checking a value to see if it is unique or if it already exists in the database. Fortunately there are a couple of ways to remedy that.

The first way is outlined in the documentation for the validation library under the heading “Callbacks: Your own Validation Functions.” I tried this and it works well, but it requires you to write the functions in your controller or model. I thought that looked messy and I wanted something a little more streamlined, so I decided to extend the validation library with my own function. Extending CodeIgniter’s libraries is pretty easy. Here’s what I came up with–I’ll explain the important lines afterward:

Continue reading