php AJAX 模式下的验证错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17097797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:15:21  来源:igfitidea点击:

Validation errors in AJAX mode

phplaravellaravel-4

提问by user2094178

Currently I use this to display validation errors via ajax:

目前我使用它通过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:

问题是我必须做些什么才能将错误从 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);
        }       

    }

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.

如果我想将字段名称作为键,我必须迭代 $rules,但即使我不使用字段名称作为键,我也必须迭代错误消息来构造 $verrors。

How could I convert $v->messages()to the equivalent of $verrorswithout the need to iterate? Since Response::json()is expecting an array instead of an object.

我怎样才能在不需要迭代$v->messages()$verrors情况下转换为等价物?因为Response::json()期待一个数组而不是一个对象。

回答by DerLola

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

最简单的方法是利用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);

This would give you a JSON response like this:

这会给你一个像这样的 JSON 响应:

{
    "success": false,
    "errors": {
        "username": [
            "The username field is required."
        ],
        "password": [
            "The password field is required."
        ]
    }
}

回答by Sports Racer

In the ajax response trying something like

在尝试类似的 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>';

回答by Sagar Naliyapara

Laravel 5 returns validation error automatically

Laravel 5 自动返回验证错误

for that you just need to do following thing,

为此你只需要做以下事情,

Controller:

控制器:

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

View:

看法:

         $.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]);
                    });
                }
            }
        });

you can build for each validationfield one <span>tag with id as field name and suffix _errorso it will show validation error with above logic like as follow,

您可以为每个validation字段构建一个<span>带有 id 作为字段名称和后缀的标签,_error因此它将显示具有上述逻辑的验证错误,如下所示,

<span id="field_error"></span>

Hope it helps :)

希望能帮助到你 :)

回答by Alexey Mezenin

There is a better way to handle validation errors when using Ajax request.

在使用 Ajax 请求时,有一种更好的方法来处理验证错误。

Create a Request class as usual, for example UploadFileAjaxRequest:

像往常一样创建一个请求类,例如UploadFileAjaxRequest

public function rules()
{
    return [
        'file' => 'required'
    ];
}

Use it in a controller method:

在控制器方法中使用它:

public function uploadFileAjax(UploadFileAjaxRequest $request)

If there is any error, it will return an array of errors which you can use in JS:

如果有任何错误,它将返回一个错误数组,您可以在 JS 中使用这些错误:

$.ajax({
    ....
    error: function(data) {
        var errors = data.responseJSON; // An array with all errors.
    }
});

回答by omarjebari

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:

顺便说一下,我正在使用 Laravel 5.1,但我认为它的基本原理应该适用于其他版本。Laravel 自动发回验证错误响应。您可以在控制器中执行以下操作:

public function processEmail(Request $request)
{
    $this->validate($request, [
        'email' => 'required|email'
    ]);
    return response()->json(['message'=>'success']);
}

Then in your javascript (i'm using jQuery here):

然后在你的 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);
});

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.

如果您查看控制台上的输出,您很快就会看到如何从 Laravel 发回的响应中获取您想要的任何内容。在该响应中,错误消息在 json 中作为键值对,其中键是验证失败的字段的名称,在我的示例“电子邮件”中。请记住确保在您的 routes.php 文件中设置了 ajax 路由,并且方法 (get/post) 与 javascript 中的方法匹配。

回答by Rakesh Mishra

I handled it using this way for laravel 5.5

我用这种方式处理了 laravel 5.5

Html code

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>

Controller validation code

控制器验证码

 // Validate form data
    $validatedData = request()->validate([
      'mandapName' => 'required',
      'location' => 'required',
      'landmark' => 'required',
      'description' => 'required',
      'contactNo' => 'required',
      'slug' => 'required',
      'functional' => 'required'
    ]);

And in javascript

在 javascript 中

     $.ajax({
        //.....Your ajax configuration
        success: function (data) {
            // Success code

        },
        error: function (request, status, error) {
            $('[name="mandapName"]').next('span').html(request.responseJSON.errors.mandapName);
            //.......
        }
    });

回答by Seo Era

Try this code. It works well:

试试这个代码。它运作良好:

$.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>")
          });

        }

    });

});