Dropzone.js and form validation

2019-06-14 09:54发布

Is it possible not to break the nice Rails form validation errors displayed after marking the whole form the 'dropzone' class?

Now, when I try to submit the form, nothing changes and the page stays at it was without providing any info for user which fields doesn't meet the requirements. Controller renders JSON response (dropzone using consequence) which seems to not be processed by the view.

Thank you in advance for your quick response.

2条回答
该账号已被封号
2楼-- · 2019-06-14 10:02

You need to parse the JSON response into your js callback yourself, something like this:

   Dropzone.options.filedrop = {
      init: function () {
        this.on("complete", function (file, jsonResponse) {
          console.log(jsonResponse);
          //do stuff with the jsonResponse here
        });
      }
    };
查看更多
在下西门庆
3楼-- · 2019-06-14 10:04

My workaround for this problem:

Dropzone.options.filedrop = {
    init: function () {
        // Other triggers not listed
        // ...

        this.on("error", function (file, response) {
            // Gets triggered when the files have successfully been sent.
            // Redirect user or notify of success.

            // Build an unordered list from the list of errors
            var _ref, _results, _i, _len;
            if ($.isPlainObject(response)) { // Check if response is in JSON format for showing standard form errors
                // Remove errors from accepted image
                file.previewElement.classList.remove("dz-error");
                _ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");
                _results = [];
                for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                    node = _ref[_i];
                    _results.push(node.textContent = null);
                }

                file['status'] = 'success';
                console.log("acceptedImage: " + JSON.stringify(file));

                var json = response;
                var errorText = "<div id=\"error_explanation\"><h2>" + Object.keys(json).length + " errors prohibited this thing from being saved:</h2><ul>";
                $.each(json, function (key, value) {
                    errorText += "<li>" + key.capitalize() + ' ' + value[0] + "</li> ";
                });
                errorText += "</ul></div>";
                console.log("errorText: " + errorText);

                // Insert error list into form
                $('.errors_placeholder').html(errorText);
            } else {
                if (myDropzone.files.length > 1) {
                    myDropzone.removeFile(myDropzone.files[0]);
                }
            }
        });
    }
};
查看更多
登录 后发表回答