Scott Nellé.com

Archive for September, 2008

Extending CodeIgniter’s Validation Library To Check For Unique Values

Thursday, September 11th, 2008

Updated November 4, 2008: This extension has been updated slightly to work with CI’s new form validation class, added with version 1.7.0. If you’re using an older version of CI you should still use the extension on this page. If you’re using 1.7.0 or later, you should check out the updated extension.

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:

(more…)