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.
Laravel 5 returns validation error automatically
for that you just need to do following thing,
Controller:
View:
you can build for each
validation
field one<span>
tag with id as field name and suffix_error
so it will show validation error with above logic like as follow,Hope it helps :)
I'm using Laravel 5.1 by the way but i think the fundamentals of this should apply to other versions. Laravel sends back the validation error response automatically. You can just do the following in your controller:
Then in your javascript (i'm using jQuery here):
If you look at the output on the console you'll soon see how to grab anything you want from the response sent back by Laravel. In that response the error messages are in json as key-value pairs where the key is the name of the field that failed validation, in my example 'email'. Remember to ensure the ajax route is set up in your routes.php file and the method (get/post) matches that in the javascript.
The easiest way is to leverage the
MessageBag
object of the validator. This can be done like this:This would give you a JSON response like this:
There is a better way to handle validation errors when using Ajax request.
Create a Request class as usual, for example
UploadFileAjaxRequest
:Use it in a controller method:
If there is any error, it will return an array of errors which you can use in JS:
I handled it using this way for laravel 5.5
Html code
Controller validation code
And in javascript
In the ajax response trying something like