Dropzone.js与其他形式相结合 - 需要html5验证

时间:2017-01-08 05:44:36

标签: javascript jquery html file-upload dropzone.js

您好我使用dropzone并将其与其他表单结合使用。问题是e.preventDefault();使我的html5验证属性(required)丢失。但如果我没有e.preventDefault();,它将提交其他表格而不上传我的文件。我该怎么办?

这是我的完整代码

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="dropzone.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="dropzone.js"></script>
    <script>
        Dropzone.options.myDropzone= {
    url: 'upload.php',
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 50,
    maxFiles: 50,
    maxFilesize: 1,
    acceptedFiles: 'image/*',
    addRemoveLinks: true,
    success: function(file, response){
        window.location = "http://www.google.com";

    },
    init: function() {
        dzClosure = this; // Makes sure that 'this' is understood inside the functions below.

        // for Dropzone to process the queue (instead of default form behavior):
        document.getElementById("submit-all").addEventListener("click", function(e) {
            // Make sure that the form isn't actually being sent.
            e.preventDefault();
            e.stopPropagation();
            dzClosure.processQueue();
        });

        //send all the form data along with the files:
        this.on("sendingmultiple", function(data, xhr, formData) {
            formData.append("firstname", $("#firstname").val());
            formData.append("lastname", $("#lastname").val());
        });
    }
}
    </script>
</head>
<body>
    <form action="upload.php" enctype="multipart/form-data" method="POST">
    <input type="text" id ="firstname" name ="firstname" required/>
    <input type="text" id ="lastname" name ="lastname" required/>

    <div class="dropzone" id="myDropzone"></div>
    <button type="submit" id="submit-all"> upload </button>
    </form>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

当您使用dropzone.processqueue()提交表单时,dropzone不知道输入是必需的,我认为最简单的方法是使用javascript手动验证同一事件中输入的值在处理队列之前,您有提交按钮的监听器。

一个例子可以是:

init: function() {
    dzClosure = this; // Makes sure that 'this' is understood inside the functions below.

    document.getElementById("submit-all").addEventListener("click", function(e) {
        e.preventDefault();
        e.stopPropagation();

        var validFirstName = document.getElementById("firstname").checkValidity();
        var validLastName = document.getElementById("lastname").checkValidity();

        if (!validFirstName || !validLastName) {
            // Here you can handle the empty input case, color the inputs red or whatever
            return false;

        } else {
            dzClosure.processQueue();
        }
    });

}