user1033600
user1033600

Reputation: 289

CodeIgniter: How can I display single validation error?

If I used this

<?= validation_errors(); ?>

the result is

Username field is required
Password field is required
<textbox for username>
<textbox for password>

what I actually need is to display those errors inline with their element

example:

<textbox for username> Username field is required
<textbox for password> Password field is required

Upvotes: 5

Views: 19653

Answers (3)

jinx
jinx

Reputation: 1

I was looking for a different kind of answer when I searched for this question. So I'd like to share my solution to the problem I was having which was "How can I display a single validation error?"

The solution is to run the validation routine before each subsequent form validation rule. That way only the first error is reported.

        $this->form_validation->set_rules('username', 'Username', 'callback_check_username');

        if ($this->form_validation->run() == TRUE){
            $this->form_validation->set_rules('password', 'Password', 'callback_check_password');
        } 

Upvotes: -1

Moyed Ansari
Moyed Ansari

Reputation: 8461

In order to display error individually you should use the function form_error('username'). And for you to get a value of a field being checked, use the function set_value('username').

For these two functions to work, you would have had to, in your controller, set a rule for the 'username' field. Where you specify wich validation rules apply to that field.

<?php echo form_error('username'); ?>
<input type="text" name="username" value="<?php echo set_value('username'); ?>">

Here is a simple tutorial about form Login

Upvotes: 9

No Results Found
No Results Found

Reputation: 102745

This is covered in the user guide:

http://codeigniter.com/user_guide/libraries/form_validation.html#individualerrors

Showing Errors Individually

If you prefer to show an error message next to each form field, rather than as a list, you can use the form_error() function.

So if your field name is username, you would use form_error('username').

Important Note: If you use an array as the name of a form field, you must supply it as an array to the function. Example:

<?php echo form_error('options[size]'); ?>

This is a shortcut for $this->form_validation->error(), which you can also use if you desire.

Upvotes: 4

Related Questions