Drew
Drew

Reputation: 6862

Codeigniter Show Individual Custom Error

I am trying to validate my login form and I have rules on my Username and Password fields.

$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

So my callback_check_database function is on the Password field.

So in my function for check_database, I have:

$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;

So I am setting the custom message that I want to display.

In my view, I want to individually show that check_database error. I don't want to show any of the other errors.

Here is what I have tried:

// does not work
<?php echo form_error('check_database'); ?>

// this works
<?php echo form_error('password'); ?>

so since it is for the Password field, it will only show when I echo the password errors. But that means, since password is a required field, if I don't type anything in it's going to display an error saying that the Password field is required.

Is there a way to only display my custom error message that I set?

Upvotes: 4

Views: 2750

Answers (1)

Laurence
Laurence

Reputation: 60048

You can solve this in two different ways. Both have advantages and disadvantages.

Option 1:

$this->form_validation->set_rules('password', 'Password', 'callback_check_database');

Then inside the callback_check_database just include a check to make sure $value != "" (which replicates the "required" field).

Note: you should NOT use xss_clean on a password field anyway (since it will alter the password - google it and you'll see examples), and there is zero benefit gained assuming you are hashing the password.

Option 2:

Inside your view file, simply type

<?php if (form_error('password'))
   {
        echo "Invalid username or password";
   } 
?>

This means you are not actually echoing the error, you are simply checking if an error for the password field exists, and regardless what it is, you only show the text above.

Upvotes: 3

Related Questions