AJAX模式下的验证错误 [英] Validation errors in AJAX mode
问题描述
当前,我使用它来通过ajax显示验证错误:
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.
问题是我必须要做的是将错误从laravel传输到ajax:
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);
}
}
如果我想将字段名称用作键,则必须迭代$ rules,但是即使我不使用字段名称作为键,也必须迭代错误消息以构造$ verrors.
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.
如何将$v->messages()
转换为$verrors
的等效项而无需进行迭代?由于Response::json()
期望使用数组而不是对象.
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.
推荐答案
最简单的方法是利用验证器的MessageBag
对象.可以这样完成:
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);
这将为您提供如下的JSON响应:
This would give you a JSON response like this:
{
"success": false,
"errors": {
"username": [
"The username field is required."
],
"password": [
"The password field is required."
]
}
}
这篇关于AJAX模式下的验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!