目前我使用它来通过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();
}
它工作正常,完全符合我的需要。
问题是我必须做的就是将错误从laravel传输到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。
如何在不需要迭代的情况下将$v->messages()
转换为相当于$verrors
?因为Response::json()
期待一个数组而不是一个对象。
最简单的方法是利用验证器的MessageBag
对象。这可以这样做:
// 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响应:
{
"success": false,
"errors": {
"username": [
"The username field is required."
],
"password": [
"The password field is required."
]
}
}
在ajax响应尝试类似的东西
.fail(function( data ) {
var response = JSON.parse(data.responseText);
var errorString = '<ul>';
$.each( response.errors, function( key, value) {
errorString += '<li>' + value + '</li>';
});
errorString += '</ul>';
Laravel 5自动返回验证错误
为此,你只需要做以下事情,
public function methodName(Request $request)
{
$this->validate($request,[
'field-to-validate' => 'required'
]);
// if it's correctly validated then do the stuff here
return new JsonResponse(['data'=>$youCanPassAnything],200);
}
$.ajax({
type: 'POST',
url: 'url-to-call',
data: {
"_token": "{{ csrf_token() }}",
"field": $('#field').cal()
},
success: function (data) {
console.log(data);
},
error: function (reject) {
if( reject.status === 422 ) {
var errors = $.parseJSON(reject.responseText);
$.each(errors, function (key, val) {
$("#" + key + "_error").text(val[0]);
});
}
}
});
你可以为每个validation
字段构建一个<span>
标签,其id为字段名称和后缀_error
,因此它将显示上述逻辑的验证错误,如下所示,
<span id="field_error"></span>
希望能帮助到你 :)
我顺便使用Laravel 5.1,但我认为其基本原理应该适用于其他版本。 Laravel自动发回验证错误响应。您可以在控制器中执行以下操作:
public function processEmail(Request $request)
{
$this->validate($request, [
'email' => 'required|email'
]);
return response()->json(['message'=>'success']);
}
然后在你的javascript(我在这里使用jQuery):
var params = {email: '[email protected]'};
$.ajax({
url: '/test/example',
method: 'POST',
data: params
})
.done(function( data ) {
// do something nice, the response was successful
})
.fail(function(jqXHR, textStatus, errorThrown) {
var responseMsg = jQuery.parseJSON(jqXHR.responseText);
var errorMsg = 'There was a general problem with your request';
if (responseMsg.hasOwnProperty('email')) {
errorMsg = responseMsg.email;
console.log(errorMsg);
}
// This will help you debug the response
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
如果您查看控制台上的输出,您很快就会看到如何从Laravel发回的响应中获取您想要的任何内容。在该响应中,错误消息在json中作为键值对,其中键是验证失败的字段的名称,在我的示例“email”中。请记住确保在routes.php文件中设置了ajax路由,并且方法(get / post)与javascript中的方法匹配。
使用Ajax请求时,有一种更好的方法来处理验证错误。
像往常一样创建一个Request类,例如UploadFileAjaxRequest
:
public function rules()
{
return [
'file' => 'required'
];
}
在控制器方法中使用它:
public function uploadFileAjax(UploadFileAjaxRequest $request)
如果有任何错误,它将返回一个可以在JS中使用的错误数组:
$.ajax({
....
error: function(data) {
var errors = data.responseJSON; // An array with all errors.
}
});
我使用这种方式处理laravel 5.5
Html代码
<div class="form-group padding">
<label for="">Kalyan Mandap Name <span class="text-danger">*</span></label>
<input type="text" class="form-control" placeholder="Enter Kalyan Mandap Name" id="mandapName" name="mandapName" value = "<?php echo (isset($mandapDetails['vchKalyanMandapName'])) ? $mandapDetails['vchKalyanMandapName'] : ""; ?>" required="required">
<span class="text-danger">{!! $errors->first('mandapName', ':message') !!} </span>
</div>
控制器验证码
// Validate form data
$validatedData = request()->validate([
'mandapName' => 'required',
'location' => 'required',
'landmark' => 'required',
'description' => 'required',
'contactNo' => 'required',
'slug' => 'required',
'functional' => 'required'
]);
并在JavaScript中
$.ajax({
//.....Your ajax configuration
success: function (data) {
// Success code
},
error: function (request, status, error) {
$('[name="mandapName"]').next('span').html(request.responseJSON.errors.mandapName);
//.......
}
});
试试这个代码。效果很好:
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$("#sendData").submit(function(e)
{
e.preventDefault();
var formData = new FormData(jQuery('#sendData')[0]);
$.ajax({
type:'POST',
url:"/your(URL)",
data:formData,
contentType: false,
processData: false,
success:function(data)
{
alert(data);
},
error: function(xhr, status, error)
{
$.each(xhr.responseJSON.errors, function (key, item)
{
$("#errors").append("<li class='alert alert-danger'>"+item+"</li>")
});
}
});
});