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_unique | Yes | Returns 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.
Table of Contents
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; } }