【问题标题】:Dropzone.js and displaying request validation errors in Laravel 5.1Dropzone.js 并在 Laravel 5.1 中显示请求验证错误
【发布时间】:2016-05-22 17:22:39
【问题描述】:

我正在使用 dropzone.js 上传文件。在我的控制器方法中,我设置了以下验证:

$this->validate($request, ['logo' => 'image|mimes:jpg,jpeg,gif']);

如果验证失败,它会抛出一个 422 服务器响应,验证错误为 json

{"logo":["The logo must be an image.","The logo must be a file of type: jpg, jpeg, gif."]}

使用 dropzone.js 如何解析错误并插入到以下<p> 标签:

@if ($errors->has('logo')) <p class="help-block" id="logo-error">{{ $errors->first('logo') }}</p> @endif

我在 dropzone 脚本中声明了一个错误事件,但是当我执行 console.log 时似乎什么也没出现:

var baseUrl = "{{ url('/') }}";
Dropzone.autoDiscover = false;

$("#my-dropzone").dropzone({
  url: baseUrl + "/upload",
  paramName: "logo",
  uploadMultiple: false,
  maxFiles: 1,
  dictDefaultMessage: '',
  init: function() {
    this.on("addedfile", function(file) {
      console.log('addedfile...');
      if (this.files[1]!=null){
        this.removeFile(this.files[0]);
      }
    });
    this.on("thumbnail", function(file, dataUrl) {
      console.log('thumbnail...');
      $('.dz-image-preview').hide();
      $('.dz-file-preview').hide();
    });
    this.on("sending", function(file, xhr, formData) {
      formData.append("_token", $('meta[name="csrf-token"]').attr('content'));
    });
    this.on("success", function(file, res) {
      console.log('upload success...');
      $('#img-thumb').attr('src', res.path);
      $('input[name="logo"]').val(res.path);
    });

  },
  error: function(file, response) {
    console.log(response);
  }
});

【问题讨论】:

标签: jquery ajax validation laravel-5.1 dropzone.js


【解决方案1】:

你需要在这里使用 jQuery。由于您使用的是 Laravel 验证,因此它将返回错误状态。这样我们就可以在您发出的 AJAX 请求的错误事件中编写所需的任何内容,即。此处的 dropzone 初始化。示例代码如下所示,

success: function(file, response) {
        $('.profile-image-wrapper').removeClass('has-error');
        $('.profile-image-error').html('');
    },
    error: function(file, response) {
        var $message = response.errors.profilePhoto;
        $('.profile-image-wrapper').addClass('has-error');
        $('.profile-image-error').html('<strong>' +  $message + '</strong');
    },

我的 dropzone 初始化的“paramName”属性是“profilePhoto”。所以错误也会以相同的顺序出现。

【讨论】:

    猜你喜欢
    • 2016-08-17
    • 2015-09-24
    • 2020-04-28
    • 2017-11-07
    • 1970-01-01
    • 2016-03-11
    • 2017-07-16
    • 2016-06-28
    • 1970-01-01
    相关资源
    最近更新 更多