Jonathan Clark
Jonathan Clark

Reputation: 20538

How to get validation errors in an array?

I am developing an REST API using Codeigniter. I need to have all error messages from Form validation in array format so that I can easily respond in either JSON or XML.

Right now Codeigniter is delivering error messages with <p> as delimiters (see below) but that is not good for a REST based API.

<p>There was an error with this item</p>

How can I get errors in an array?

Thankful for all input!

Upvotes: 1

Views: 1014

Answers (2)

Chris Schmitz
Chris Schmitz

Reputation: 8247

The form validation library stores errors in an array and loops through them to generate the error string. They are stored in a private variable called $_error_array. You could extend the library with a simple method that returns the error array.

class MY_Form_validation extends CI_Form_validation
{
    function get_error_array()
    {
        return $this->_error_array;
    }
}

I assume you are familiar with extending core CI libraries, but this extension of the form validation library will give you a method to return the errors as an array with the name attribute's value as the key and the message as the value. I tested it out on one of my projects and it worked fine.

Upvotes: 1

Lars
Lars

Reputation: 5799

You can transform it easily:

/**
 * @param $errors string
 * @return array
 */
function transformErrorsToArray ($errors) {
    $errors = explode('</p>', $errors);
    foreach ($errors as $index => $error) {
        $error = str_replace('<p>', '', $error);
        $error = trim($error);
        // ... more cleaning up if necessary
        $errors[$index] = $error
    }
    return $errors;
}

Upvotes: 1

Related Questions