Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

Array
{
  '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:

$this->form_validation->required($user_name);
$this->form_validation->required($password);

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.
like image 750
Sabya Avatar asked Jan 22 '09 05:01

Sabya


1 Answers

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.

like image 169
Sabya Avatar answered Oct 11 '22 21:10

Sabya