Skip to content

Instantly share code, notes, and snippets.

@Sitebase
Created March 11, 2013 14:47
Show Gist options
  • Save Sitebase/5134745 to your computer and use it in GitHub Desktop.
Save Sitebase/5134745 to your computer and use it in GitHub Desktop.
CodeIgniter unique validator that has support for excluding a specific row.
public function unique($value, $params)
{
$CI =& get_instance();
list($table, $field, $exclude_field, $exclude_value) = array_pad(explode('.', $params, 4), 4, NULL);
$CI->form_validation->set_message('unique', 'The %s that you requested is unavailable.');
$CI->db->select('COUNT(*) AS dupe')->from($table)->where($field, $value)->limit(1);
if($exclude_field AND $exclude_value)
{
$CI->db->select($exclude_field . ' AS id');
$CI->db->where($exclude_field . ' !=', $exclude_value);
}
$row = $CI->db->get()->row();
return ($row->dupe > 0) ? FALSE : TRUE;
}
@Sitebase
Copy link
Author

Usage

Check for total uniqueness:

unique[table.field]

Check if unique but exclude row where field user_id is 40 from. This is handy for checking uniqueness when you want to update a row.

unique[table.field.user_id.40]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment