Search code examples
codeigniter

Form_validation errors into array


I have a code for form validating in my CodeIgniter app:

$this->load->library('form_validation');

$this->form_validation->set_rules('message', 'Message', 'trim|xss_clean|required');
$this->form_validation->set_rules('email', 'Email', 'trim|valid_email|required');

if($this->form_validation->run() == FALSE)
{
    // some errors
}
else
{
    // do smth
    $response = array(
        'message' => "It works!"
    );
    echo json_encode($response);
}

The form is AJAX-based, so frontend have to receive a JSON array with form errors, for example:

array (
  'email' => 'Bad email!',
  'password' => '6 symbols only!',
)

How to get such list or array with form validation errors in CodeIgniter?


Solution

  • You just echo validation_errors() from your controller.

    have your javascript place it in your view.

    PHP

    // controller code
    if ($this->form_validation->run() === TRUE)
    {
        //save stuff
    }
    else
    {
        echo validation_errors();
    }
    

    Javascript

    // jquery
    $.post(<?php site_url('controller/method')?>, function(data) {
      $('.errors').html(data);
    });
    

    If you really want to use JSON, jquery automatically parses JSON. You can loop through it and append into your html.


    in case you need validation errors as array you can append this function to the form_helper.php

    if (!function_exists('validation_errors_array')) {
    
       function validation_errors_array($prefix = '', $suffix = '') {
          if (FALSE === ($OBJ = & _get_validation_object())) {
            return '';
          }
    
          return $OBJ->error_array($prefix, $suffix);
       }
    }