0

I have a form where I am using dropzone.js for file upload. Now I am validating all the input fields. But i'm not able to validate the file before submission. If the file is uploaded, then the submission should work. Otherwise it should throw an error like - "please upload the file". How can i achieve this?

HTML code:

 <form action="/action">
        <div class="form-row">
           <div class="form-group col-md-6">
              <input type="text" class="form-control" id="first_name" name="first_name" placeholder="First Name" required>
           </div>
           <div class="form-group col-md-6">
              <input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name" required>
           </div>
        </div>
        <div class="form-row">
           <div class="form-group col-md-12">
             <textarea class="form-control" id="message" name="message" placeholder="Message"></textarea>
           </div>
        </div>
        <div class="form-row">
           <div id="resume" class="dropzone form-control"></div>
        </div>
        <input type="submit" class="btn btn-primary mt-10" id="item-submit" value="submit">
    </form>

Javascript :

<script type="text/javascript">

    $(document).ready(function () {

        $("div#resume").dropzone({ url: "/change-this-later" });
        var dropzone3;
        Dropzone.autoDiscover = false;
        dropzone3 = new Dropzone('#resume', {
                maxFiles: 1,
            });
        $('#item-submit').click(function(e) {
            e.preventDefault();
            e.stopPropagation();
            if ($('form#resume').valid()) {};
        });
    });

</script>
Varghese Mathai
  • 411
  • 3
  • 11
Sam
  • 1,381
  • 4
  • 30
  • 70

2 Answers2

0

You can add a callback event which is called if the upload is successful

//indicates file upload is complete and is successful
var uploaded = false;

$("div#resume").dropzone({
    url: "/change-this-later",
    success: function (file, response) {
            uploaded = true;
    }
});

//Check the value of 'uploaded' when validating rest of fields
Varghese Mathai
  • 411
  • 3
  • 11
0

So I come around this. Since I submit all my images and fields in the same button, I just acceded to the files array in side the dropzone and validate that it's lenght wasn't 0. $animalImage is my dropzone.

var validateImages = function (animal) {
    if ($animalImage.files.length == 0) {
        swal({
            title: 'Advertencia',
            type: 'info',
            html: "Debe de guardar al menos una imágen",
            showCloseButton: true,
            focusConfirm: false
        });
        return false;
    }
    return animal;
};

Hope it helps, side note a submit trough ajax so I just used dropzone for the user experience.

Danielle Lpz
  • 312
  • 3
  • 14