Validation errors in AJAX mode

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

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

    Create a Request class as usual, for example 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:

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

提交回复
热议问题