How to Use is_unique in Form Update Validation in CodeIgniter

If you’re using CodeIgniter for your web development, you may have come across the need to use the is_unique form validation rule when updating a record. Essentially, this rule checks to see if a given value is unique in the database table. However, there’s a catch – by default, the is_unique rule will also check the record being updated, and if the value hasn’t changed, it will return false (indicating that the value is not unique).

Hence, if you are updating an old value, the form blocks the submission because it checks the data against its own record set.

if(trim($user->zipcode) != trim($this->input->post('zipcode'))){
    $this->form_validation->set_rules('zipcode', 'Zip', 'required|is_unique[user.zipcode]');
} else {
    $this->form_validation->set_rules('zipcode', 'Zip', 'required');
}
//create a custom rule
$this->form_validation->set_rules('product', 'Product', 'callback_product_check');

public function product_check($product){
    //query database here then compare data
    if ($duplicated){
            $this->form_validation->set_message('product_check', 'The product is duplicated');
            return FALSE;
    } else {
            return TRUE;
    }
}

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close