Sunday, October 13, 2013

Form Validation for Unique Values in Codeigniter

CodeIgniter has a nice Form_validation class. It comes with several validation rules:


ss_4


 


This might be considered more of an extension than a hack. Nevertheless, we are going to take a core CodeIgniter library and improve it.


Create: “application/libraries/MY_Form_validation.php


class MY_Form_validation extends CI_Form_validation {

function unique($value, $params) {

$CI =& get_instance();
$CI->load->database();

$CI->form_validation->set_message('unique',
'The %s is already being used.');

list($table, $field) = explode(".", $params, 2);

$query = $CI->db->select($field)->from($table)
->where($field, $value)->limit(1)->get();

if ($query->row()) {
return false;
} else {
return true;
}

}
}

Now you can use the unique validation rule. ;)


 



Form Validation for Unique Values in Codeigniter

No comments:

Post a Comment