How to show validation errors using redirect in codeigniter?

I know it's a bit late but this method works wonders for me.

If you are validating your form in a different function than the one the form is loaded in, you can send your validation_errors() to any page that you redirect() by passing the validation_errors() method to $this->session->set_flashdata() like so:

if ($this->form_validation->run() == FALSE) {

    $this->session->set_flashdata('error', validation_errors());

    redirect('/');
}

In your controller functions where you would like your errors or messages to be received you can then set them to the $data array like so:

if (!empty($this->session->flashdata('message'))) {

    $data['message'] = $this->session->flashdata('message');
} elseif (!empty($this->session->flashdata('error'))) {

    $data['error'] = $this->session->flashdata('error');
}

At the top of my views I usually include:

<?php if (isset($message)) {

    echo '<p class="alert alert-info">'.$message.'</p>';
} elseif (isset($error)) {

    echo '<p class="alert alert-danger"><strong>Error: </strong>'.$error.'</p>';
}?>

Using twitter bootstrap classes to format the messages helps to differentiate them.

I included the message flashdata so that you can see how whatever type of message or error you want to send, you are able to format them differently for all information, warning, success and error messages.


As per my comment:

function index()
{
    $this->load->library('form_validation');
    $data = array
    (
        'Param' => 'Value'
    );
    if($this->input->post('cellphone', true) !== false)
    {
        if($this->form_validation->run() != FALSE)
        {
            echo '<pre>' . print_r($_POST, true) . '</pre>';
        }
    }
    $this->load->view('index', $data);
}

First, you need to change your form so it points to the current page, i.e. current_url() or site_url('controller/index').

When you go to the index without posting, it will simply skip the validation. Upon submitting your form, it will run the validation.

You can then use the built in form_error or validation_errors methods to display the errors within your index view.


I found the way to do it. Redirecting does not keep the data to be shown. I used the code below to solve the problem:

if($this->form_validation->run() == FALSE)
{
    $this->index();
}