Search code examples
phpformscodeignitervalidation

Custom error message using CodeIgniter Form Validation


I want to make some custom error messages in my CodeIgniter forms. I've tried using

$this->form_validation->set_message('is_unique[users.username]', 'The username is already taken');

However I can't get it working.

Editing the form_validation_lang.php file is not good enough, as is_unique will be The username is already taken for usernames, and The e-mail is already registered for mails.

How can I make this custom error message?

Here's a snippet from my code:

$this->form_validation->set_message('is_unique[users.username]', 'The username is already taken');

// Check if username has changed
if ($this->input->post('username') !== $user->username) {
    $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|max_length[20]|is_unique[users.username]');
}

Solution

  • Right way of doing this is by passing a string format

    $this->form_validation->set_message('is_unique', 'The %s is already taken');
    

    So, then only we can able to get message like "This Username is already taken" or "This Email is already taken".