Form_validation errors into array
Asked Answered
I

9

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?

Interracial answered 13/1, 2011 at 4:55 Comment(1)
possible duplicate of CodeIgniter Form Validation - Get the Result as "array" Instead of "string"Eckert
D
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);
   }
}
Deflate answered 13/1, 2011 at 5:4 Comment(0)
S
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

Superimpose answered 17/12, 2011 at 4:20 Comment(3)
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()Theosophy
$errors = $this->form_validation->error_array(); this works wellTragic
fyi, the reference link is dead now (2nd august 2022)Tayyebeb
D
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);
   }
}
Deflate answered 13/1, 2011 at 5:4 Comment(0)
A
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();
Aldine answered 30/4, 2013 at 18:55 Comment(0)
D
12

Using the latest version of codeigniter:

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

returns:

array("field"=>"message","field2"=>"message2");
Decipher answered 1/6, 2017 at 6:23 Comment(0)
G
5

Simply use...

$errors = $this->form_validation->error_array();
Goglet answered 25/9, 2017 at 9:9 Comment(0)
I
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;
    }
}
Interracial answered 13/1, 2011 at 19:7 Comment(1)
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);Alec
H
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();;

Hind answered 2/10, 2013 at 22:4 Comment(0)
D
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>

Doze answered 1/3, 2023 at 9:22 Comment(0)
P
-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.

Pelops answered 21/3, 2013 at 14:30 Comment(2)
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.Aldine
Yes it throws an error Cannot access protected property CI_Form_validation::$_error_arrayMerca

© 2022 - 2024 — McMap. All rights reserved.