Validation errors in AJAX mode

前端 未结 8 1102
盖世英雄少女心
盖世英雄少女心 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 00:56

    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:

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

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

    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.

提交回复
热议问题