AJAX模式下的验证错误

时间:2013-06-13 21:53:23

标签: php laravel laravel-4

目前我使用它来通过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()期待数组而不是对象。

9 个答案:

答案 0 :(得分:68)

最简单的方法是利用验证器的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."
        ]
    }
}

答案 1 :(得分:12)

在尝试类似

的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>';

答案 2 :(得分:4)

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>

希望有所帮助:)

答案 3 :(得分:1)

我正在使用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: 'get-from-form-input@test.com'};
$.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中的匹配。

答案 4 :(得分:1)

使用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.
    }
});

答案 5 :(得分:1)

我在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);
            //.......
        }
    });

答案 6 :(得分:0)

尝试此代码。效果很好:

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

        }

    });

});

答案 7 :(得分:0)

我做到了,尝试这个希望能帮助您解决相关字段后的渲染错误。

$("#booking_form").submit(function(e){
                e.preventDefault();
                let form_data = $("#booking_form").serialize()
                $(document).find("span.text-danger").remove();
                $.ajax({
                    url : "your-url",
                    type : "POST",
                    data : form_data,
                    success : function(response){

                    },
                    error:function (response){
                        $.each(response.responseJSON.errors,function(field_name,error){
                            $(document).find('[name='+field_name+']').after('<span class="text-strong textdanger">' +error+ '</span>')
                        })
                    }
                })
            })

答案 8 :(得分:0)

我想分享对我有用的东西:

在后端我做了一些类似于这篇文章中第一个答案指出的:

(在“$arrayValidate”中,我使用正则表达式进行验证,如果您不知道它们是如何工作的,请给我发短信,我很乐意解释)

    public function createUser(Request $request){
        
    $arrayRequest = [
        "name" => $request->name,
        "document" => $request->document,
        "password" => $request->password
    ];

    $arrayValidate = [
        "name" => ["required",'regex:/^[a-zñÑáéíóúÁÉÍÓÚ]+$/i'],
        "document" => ["required",'regex:/^\d{6,12}$/', 'unique:tb_usuarios'],
        "password" => ["required",'regex:/^.{8,}$/']
    ];

    $response = Validator::make($arrayRequest, $arrayValidate);

    if($response->fails()){
        return Response::json([
            'response' => false,
            'errors' => $response->getMessageBag()->toArray()
        ], 422);
    }

    $response = User::create([
        "name" => $request->name,
        "document" => $request->document,
        "password" => Hash::make($request->password)
    ]);

    return Response::json(['success' => true], 200);
    }

在前端使用 Javascript,我们获得准备处理的验证响应:

    axios({
        url: `create`,
        method: 'post',
        responseType: 'json',
        data: datos // Your data here
    })
    .then((res) => {
        if(res.status==200) {
            return res.data
        }
        console.log(res)
    })
    .catch((error) => {
        // Here we obtain an object of arrays with the response of the validation, which fields are correct and which ones are incorrect
        console.log(error.response.data.errors)            
    })
    .then((res) => {
        console.log(res)    
    })
相关问题