17

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?

1

9 Answers 9

34

application/libraries/MY_Form_validation.php

<?php
class MY_Form_validation extends CI_Form_validation
{
  function __construct($config = array())
  {
    parent::__construct($config);
  }

  function error_array()
  {
    if (count($this->_error_array) === 0)
      return FALSE;
    else
      return $this->_error_array;
  }
}

Then you could try the following from your controller:

$errors = $this->form_validation->error_array();

Reference: validation_errors as an array

Sign up to request clarification or add additional context in comments.

3 Comments

It's a protected variable though so that won't work, therefor as your reference states - override form_validation and return it trough error_array()
$errors = $this->form_validation->error_array(); this works well
fyi, the reference link is dead now (2nd august 2022)
21

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);
   }
}

Comments

19

If you prefer a library method, you can extend the Form_validation class instead.

class MY_Form_validation extends CI_Form_validation {

    public function error_array() {
        return $this->_error_array;
    }

}

and subsequently call it in your controller/method.

$errors = $this->form_validation->error_array();

Comments

12

Using the latest version of codeigniter:

print_r($this->form_validation->error_array());

returns:

array("field"=>"message","field2"=>"message2");

Comments

5

Simply use...

$errors = $this->form_validation->error_array();

Comments

1

I've extended form validation helper:

if ( ! function_exists('validation_errors_array'))
{
    function validation_errors_array()
    {
        if (FALSE === ($OBJ =& _get_validation_object()))
        {
            return '';
        }
        // No errrors, validation passes!
        if (count($OBJ->_error_array) === 0)
        {
            return '';
        }
        // Generate the error string
        $array = '';
        foreach ($OBJ->_error_array as $key => $val)
        {
            if ($val != '')
            {
                $array[$key]= $val;
            }
        }
        return $array;
    }
}

1 Comment

If you want to return json formated object: echo json_encode($array, JSON_FORCE_OBJECT); but you must have php 5.3. if your php < 5.3: echo json_encode($array);
1

from : http://darrenonthe.net/2011/05/10/get-codeigniter-form-validation-errors-as-an-array/

By default, the Codeigniter Form Validation errors are returned as a string:

return validation_errors();;

Comments

0

In CI 4 I found this inside the form_helper.php

if (! function_exists('validation_errors')) {
    /**
     * Returns the validation errors.
     *
     * First, checks the validation errors that are stored in the session.
     * To store the errors in the session, you need to use `withInput()` with `redirect()`.
     *
     * The returned array should be in the following format:
     *     [
     *         'field1' => 'error message',
     *         'field2' => 'error message',
     *     ]
     *
     * @return array<string, string>
     */
    function validation_errors()
    {
        session();

        // Check the session to see if any were
        // passed along from a redirect withErrors() request.
        if (isset($_SESSION['_ci_validation_errors']) && (ENVIRONMENT === 'testing' || ! is_cli())) {
            return $_SESSION['_ci_validation_errors'];
        }

        $validation = Services::validation();

        return $validation->getErrors();
    }
}

You can implement this on views like this

# Views/example.php
<?= helper('form'); ?>

<form>
    ...
    <?php foreach(validation_errors() as $field_name => $error_message): ?>
        <?= "$field_name = $error_message <br>" ?>
    <?php endforeach ?>
</form>

Comments

-1

The solution I like best doesn't involve adding a function anywhere or extending the validation library:

$validator =& _get_validation_object();
$error_messages = $validator->_error_array;

Reference: http://thesimplesynthesis.com/post/how-to-get-form-validation-errors-as-an-array-in-codeigniter/

You should be able to call this at any point in your code. Also, it's worth noting there is a previous thread that discusses this as well.

2 Comments

Newest CodeIgniter protects _error_array property. "PHP Fatal error: Cannot access protected property..." You could extend it (MY_Form_validation) and set a new public property/method to _error_array I suppose. But this solution no longer works.
Yes it throws an error Cannot access protected property CI_Form_validation::$_error_array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.