Updating Unique Field Validation for CI 1.7.0
Tuesday, November 4th, 2008Just a quick post to keep my CodeIgniter unique field validation extension up to date. When EllisLab released CodeIgniter 1.7.0, they included a new form validation class which is meant to replace the old validation class. The old class still exists in the code for now but it’s been deprecated, so developers are urged to use the new form validation class instead. Only very minor updates are needed to my validation extension in order to make it work with the new code. These were suggested to me by commenter libre before I even had a chance to look at implementing them myself. (Thanks libre!) For everyone’s benefit, here’s the updated version of the library (and remember, use this if you’re running CodeIgniter 1.7.0 or later:)
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* MY_Form_validation Class
*
* Extends Form_Validation library
*
* Adds one validation rule, "unique" and accepts a
* parameter, the name of the table and column that
* you are checking, specified in the forum table.column
*
* Note that this update should be used with the
* form_validation library introduced in CI 1.7.0
*/
class MY_Form_validation extends CI_Form_validation {
function My_Form_validation()
{
parent::CI_Form_validation();
}
// --------------------------------------------------------------------
/**
* Unique
*
* @access public
* @param string
* @param field
* @return bool
*/
function unique($str, $field)
{
$CI =& get_instance();
list($table, $column) = split("\.", $field, 2);
$CI->form_validation->set_message('unique', 'The %s that you requested is unavailable.');
$query = $CI->db->query("SELECT COUNT(*) dupe FROM $table WHERE $column = '$str'");
$row = $query->row();
return ($row->dupe > 0) ? FALSE : TRUE;
}
}
?>
You’ll want to save this file as system/application/libraries/MY_Form_validation.php (instead of MY_Validation.php.)
When you load the library, don’t forget that it’s now called form_validation instead of just validation. There have also been some changes to the way you set your rules for the new form validation class. You can read all about this in the class documentation. Here’s the basic format, including usage of the “unique” rule from the extension:
$this->form_validation->set_rules('username','User Name','required|min_length[5]|unique[users.username]');
$this->form_validation->set_rules('emailaddress','Email Address','required|valid_email|unique[users.email]');
