CodeIgniter Forums

Full Version: Help with validation rule checking for uniqueness
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Unknown[/eluser]
Trying to write a validation rule that would check to make sure data is unique. I've seen posts that mention how to do this for validating data on insertion, but how would you do this for updating data?

Thanks in advance.
-DK

El Forum

[eluser]umefarooq[/eluser]
hi if you want to update record in database then you have to put id of the record in form if id is there while saving it will update the record, if id is not there it will insert the record.

El Forum

[eluser]Unknown[/eluser]
Understood. I'm talking specifically about validation rules to ensure that fields on the record being updated are unique. The validation function that checks for uniqueness sees the existing record and corresponding fields in the database.

For instance, my schema requires email to be unique. when I go to edit a record, but leave the email the same as before, it fails validation saying email needs to be unique. It sees the existing record's email and thinks I'm creating a new record with the same email.

I'd like to know if there is a way to create a validation rule that would take in the ID of the row being updated. That way, the validation rule could ensure unique for all records BESIDES the row being updated.

So the big question is can I do this with some kind of override in the validation helper, or do I need to do this in each controller update function?

Thanks,
-DK

El Forum

[eluser]Iván Argulo[/eluser]
Maybe it could be done with callbacks.

For example:

Code:
$this->form_validation->set_rules('username', 'Username', 'required|callback_check_user');

function check_user($user) {
// Do all stuff here
}

I remember we did this a few months ago. We use a session to store the current ID of the record, so we tested if the data exists excluding the current record.

Hope it helps you.