How to Use is_unique in Form Validation on UPDATE in CodeIgniter 3

CodeIgniter provides a comprehensive form validation and data prepping class that helps developers make form submission easier.

Among the rule, is_unique is a useful one to check whether a field exists in the database.

is_uniqueYesReturns FALSE if the form element is not unique to the table and field name in the parameter. Note: This rule requires Query Builder to be enabled in order to work.is_unique[table.field]

It works perfectly in situations when you need to create a new record. However, it doesn’t when you need to update an old record. This rule checks the data against its own record set so it always returns a duplication.

Add the rule when the data is different

This method is simple. We compare the original data with the newly submitted one. If they are different, we add is_unique rule, otherwise, don’t add the rule.

if(trim($user->phone) != trim($this->input->post('phone'))){
	$this->form_validation->set_rules('phone', 'Phone', 'required|is_unique[user.phone]');
} else {
	$this->form_validation->set_rules('phone', 'Phone', 'required');
}

Create your own validation methods

CodeIgniter 3 validation system supports callbacks to your own validation methods. We can create a new callback called callback_phone_check to check for the phone number.

$this->form_validation->set_rules('phone', 'Phone', 'callback_phone_check');

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

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

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