Sabya Sabya - 1 year ago 60
PHP Question

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:

, and
. Among them
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download