is_unique for codeigniter form validation

is_unique for codeigniter form validation

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling Unique Constraints in CodeIgniter Form Validation

When building a user management system, ensuring that usernames are unique is a standard requirement. In CodeIgniter, this is typically handled by the is_unique validation rule. However, scenarios involving edit forms introduce a specific logical conflict: how do you validate uniqueness without rejecting a valid update where the username hasn't changed?

The core issue lies in how database constraints interact with application-level validation logic. If your table has a UNIQUE constraint on the user_name column and you attempt to save a record with an existing value, the database will throw an error regardless of whether that record is the one being updated or a different one. To handle this gracefully within CodeIgniter's validation layer, you must explicitly exclude the current row from the uniqueness check during an update operation.

The most robust approach involves modifying the validation rule dynamically based on the HTTP request method. When handling a form submission for editing, you are usually identifying the record via an ID (e.g., user_id). You can detect this context by checking if the request method is PUT or PATCH, or by inspecting whether the submitted data contains the primary key identifier.

Here is how you might structure the logic in your controller:

if ($this->input->method() === 'post') {
    // Handle Create
    $rules['user_name'] = [
        'field' => 'user_name',
        'label' => 'User Name',
        'rules' => 'required|trim|xss_clean|is_unique[users.user_name]'
    ];

} elseif ($this->input->method() === 'put') {
    // Handle Update
    $rules['user_name'] = [
        'field' => 'user_name',
        'label' => 'User Name',
        'rules' => 'required|trim|xss_clean'
        // Note: We remove is_unique here for the general check
    ];

    // Perform a preliminary uniqueness check excluding the current user
    if ($this->db->where('user_name', $this->input->post('user_name'))
                 ->where('user_id !=', $this->input->post('user_id'))
                 ->get('users')->num_rows() > 0) {
        $this->form_validation->set_error('user_name', 'The username you entered is already in use.');
    }
}

By removing the is_unique rule for updates and performing a manual database query that excludes the current record (user_id != $current_id), you ensure that the validation passes if the user keeps their current name. If they attempt to change it to an existing name belonging to another user, the manual check catches it before the model saves the data.

It is important to note that relying solely on application-level logic for uniqueness checks can be brittle. Database transactions and race conditions might occur between your validation check and the actual INSERT or UPDATE statement. In high-concurrency environments, a row could be modified by another request milliseconds after your uniqueness check passes but before your save operation executes.

To mitigate this risk, consider using database-level constraints as the final line of defense. Many modern databases support ignoring unique constraint violations on the specific row being updated when certain conditions are met, though this varies by engine (e.g., MySQL's ON DUPLICATE KEY UPDATE or PostgreSQL's EXCLUDED alias). Alternatively, you can wrap your save logic in a transaction and rely on the database to throw an error if a conflict occurs outside of the current record, then handle that specific exception in your controller.

If you are maintaining a legacy CodeIgniter 3 project and need similar features with modern Laravel conventions, the ecosystem has evolved significantly. Companies like LaravelCompany often provide resources on migrating strict validation patterns to more flexible approaches found in newer frameworks, where form request classes handle these exclusions more elegantly using builder syntax. However, for existing CodeIgniter 3 applications, the conditional logic approach described above remains the standard pattern for solving this specific edge case.

Our network