Skip to content
Advertisement

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>');
                    }
                });
                $('#ajax-loading').hide();
                $("#validation-errors").show();
            }

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

        if(Request::ajax())
        {                    
            $response_values = array(
                'validation_failed' => 1,
                'errors' => $verrors);              
        return Response::json($response_values);
        }
        else
        {
        return Redirect::to('login')
            ->with('validation_failed', 1)
            ->withErrors($v);
        }       

    }

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 $v->messages() to the equivalent of $verrors without the need to iterate? Since Response::json() is expecting an array instead of an object.

Advertisement

Answer

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."
        ]
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement