CodeIgniter Form Validation - Get the Result as "array" Instead of "string"


I am writing my form validation class using CodeIgniter. Is there any way so that I can get error messages in name value pair? For example, in a sample form there are four fields: user_name, password, password_conf, and timezone. Among them user_name and password validation has failed after executing the following:

$result = $this->form_validation->run();

If the above function returns false, I want to get the errors in name value pairs like the following:

  'user_name' => 'user name is required',
  'password' => 'passord is required'

I truly want to form a JSON, which I can pass back to the AJAX call. I have a (dirty) solution: I can call validation methods one by one like the following:


Is there any other way, to get all the error messages at once in name value pair?

EDIT: I was suggested to do validation with jQuery from one of the answers:

jQuery will help in client side validation, but what about server side, there I am using CodeIgniter validation.

I have designed it so that:

  1. I post all the values using AJAX.
  2. Validate in server side (PHP).
  3. Perform the desired operation if the inputs are valid; else return error to the user.
12/31/2011 5:49:45 AM

Accepted Answer

I have found one way myself by looking into the CodeIgniter code: I have extended the library CI_Form_validation like: -

class MY_Form_validation extends CI_Form_validation
    public function getErrorsArray()
        return $this->_error_array;

I know, this is a hack, but will serve my need for the time. I hope CodeIginter team soon come up with an interface to access that array.

1/22/2009 3:05:59 PM

You can simply use,


This is from the class reference documentation of CodeIgniter.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow