I created a custom validation in Code Igniter. I have the following code but the is_FieldUnique
validation is not working. Even if, I var_dump()
the parameters still I am not getting the it was displaying. What am I doing wrong with my code below? I am not getting any return with the is_FieldUnique
but the default validation is working fine like the required
, min_length
.
In application/libraries/Customfieldvalidation.php
, I have this line of code below:
class Customfieldvalidation extends CI_Form_validation
{
public function is_FieldUnique($str, $field)
{
var_dump($str);
var_dump($field);
list($table, $field)=explode('.', $field);
$q = $this->CI->db->query("SHOW KEYS FROM $table WHERE Key_name = 'PRIMARY'")->row();
$primary_key = $q->Column_name;
if($this->CI->input->post($primary_key) > 0):
$query = $this->CI->db->limit(1)->get_where($table, array($field => $str,$primary_key.' !='=>$this->CI->input->post($primary_key)));
else:
$query = $this->CI->db->limit(1)->get_where($table, array($field => $str));
endif;
echo $query;
exit();
return $query->num_rows() === 0;
}
}
In my controller, I have this code:
class User extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('customfieldvalidation');
}
function _setRules()
{
$this->form_validation->set_rules('email_address', 'Email Address', 'required|valid_email|min_length[8]|is_FieldUnique[users.email_address]');
$this->form_validation->set_message('is_FieldUnique', '* must have a unique value');
}
}
What could be the reason that the custom field is not working? I know this could be pretty simple for everyone but I'm new to Codeigniter and starting to learn.