user2094178 user2094178 - 1 year ago 90
PHP Question

Validation errors in AJAX mode

Currently I use this to display validation errors via ajax:

if (data.validation_failed == 1)
var arr = data.errors;
$.each(arr, function(index, value)
if (value.length != 0)
$("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>');

It works fine, does exactly what I need.

The problem is what I have to do to transport the errors from laravel to ajax:

$rules = array(
'name' => 'required',
'password' => 'required'

$v = Validator::make(Input::all(), $rules);

if ( ! $v->passes())

$messages = $v->messages();

foreach ($rules as $key => $value)
$verrors[$key] = $messages->first($key);

$response_values = array(
'validation_failed' => 1,
'errors' => $verrors);
return Response::json($response_values);
return Redirect::to('login')
->with('validation_failed', 1)


If I want to have the field names as key, I have to iterate $rules, but even if I don't use field names as key, yet I have to iterate error messages to construct $verrors.

How could I convert
to the equivalent of
without the need to iterate? Since
is expecting an array instead of an object.

Answer Source

The easiest way is to leverage the MessageBag object of the validator. This can be done like this:

// Setup the validator
$rules = array('username' => 'required|email', 'password' => 'required');
$validator = Validator::make(Input::all(), $rules);

// Validate the input and return correct response
if ($validator->fails())
    return Response::json(array(
        'success' => false,
        'errors' => $validator->getMessageBag()->toArray()

    ), 400); // 400 being the HTTP code for an invalid request.
return Response::json(array('success' => true), 200);

This would give you a JSON response like this:

    "success": false,
    "errors": {
        "username": [
            "The username field is required."
        "password": [
            "The password field is required."
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download