Custom error message using CodeIgniter form validation

I want to make some error messages in my CodeIgniter. I tried using

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

However, I cannot get it to work.

Editing the form_validation_lang.php file form_validation_lang.php not good enough, since is_unique will be the username already accepted for the username and an email has already been registered for emails.

How can I create this error message?

Here is the code snippet:

 $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]'); } 
+8
php validation forms codeigniter
source share
7 answers

The proper way to do this is to pass a string format

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

So then only we can receive a message like "This Username is already taken" or "This Email is already taken" .

+21
source share

It worked for me

 $this->form_validation->set_message('is_unique', 'The username is already taken'); 
+2
source share

You’re better off like this:

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

Validation form changes %s to the label set for the field.

Hope this helps!

+2
source share

This is how you set the error message ONLY for the username:

 $this->form_validation->set_rules('username','Username','is_unique',array('is_unique' => 'The %s is already taken')); 
+1
source share

You can add your custom message to the validation_errors() after validation validation with $this->form_validation->run() == true

 if(YOUR_CONDITION){ $this->form_validation->run(); $err = validation_errors(); $err = $err. '<p>Custom validation error message</p>'. PHP_EOL; $data['err'] = $err; $this->load->view('viewname', $data); } else if ($this->form_validation->run() == true ) { #code... } else.. 

after setting your custom message to the $err variable, print it in your view.

0
source share
 create a **form_validation.php** file and use this method: "add_user_rule" => [ [ "field" => "username", "label" => "Username", "rules" => "required|trim|is_unique[users.username]", "errors" => [ 'is_unique' => 'The %s is already taken.', ], ], ], Thank You 
0
source share

You need to refer to the field name, not the rule.

Documents get a little confused about what they also call it "required."

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

It should be

$this->form_validation->set_message('username', 'The username is already taken');

Hope this helps!

-one
source share

All Articles