Validation errors in AJAX mode

前端 未结 8 851
盖世英雄少女心
盖世英雄少女心 2021-01-30 00:14

Currently I use this to display validation errors via ajax:

            if (data.validation_failed == 1)
            {
                var arr = data.errors;
            


        
相关标签:
8条回答
  • 2021-01-30 01:02

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

    0 讨论(0)
  • 2021-01-30 01:05

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

    This would give you a JSON response like this:

    {
        "success": false,
        "errors": {
            "username": [
                "The username field is required."
            ],
            "password": [
                "The password field is required."
            ]
        }
    }
    
    0 讨论(0)
提交回复
热议问题