1
I integrated Dropzone.js with a form, and would need to validate the fields. I have the following code (it’s not working, but it’s what I need to "join", in case):
var Galerias = function () {
return {
//main function to initiate the module
initForm: function() {
var form = $('#my-dropzone');
var error = $('.alert-danger', form);
var success = $('.alert-success', form);
form.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block help-block-error', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "", // validate all fields including form hidden input
errorPlacement: function (error, element) { // render error placement for each input type
if (element.parent(".input-group").size() > 0) {
error.insertAfter(element.parent(".input-group"));
} else if (element.attr("data-error-container")) {
error.appendTo(element.attr("data-error-container"));
} else if (element.parents('.radio-list').size() > 0) {
error.appendTo(element.parents('.radio-list').attr("data-error-container"));
} else if (element.parents('.radio-inline').size() > 0) {
error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
} else if (element.parents('.checkbox-list').size() > 0) {
error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
} else if (element.parents('.checkbox-inline').size() > 0) {
error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
} else {
error.insertAfter(element); // for other inputs, just perform default behavior
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
success.hide();
error.show();
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.form-group').addClass('has-error'); // set error class to the control group
},
unhighlight: function (element) { // revert the change done by hightlight
$(element)
.closest('.form-group').removeClass('has-error'); // set error class to the control group
},
success: function (label) {
label
.closest('.form-group').removeClass('has-error'); // set success class to the control group
},
submitHandler: function (form) {
success.show();
error.hide();
$('button[type="submit"]', form).prop("disabled", true);
$('button[type="submit"]', form).html('<i class="fa fa-spinner fa-spin"></i> Aguarde, enviando imagens...');
}
});
//apply validation on select2 dropdown value change, this only needed for chosen dropdown integration.
$('.select2me', form).change(function () {
form.validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
});
},
initDropzone: function() {
Dropzone.options.myDropzone = {
previewsContainer: ".dropzone-previews",
clickable: ".dropzone-previews",
acceptedFiles: 'image/*',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 500,
maxFilesize: 5, // mb
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
$('button[type="submit"]', form).prop("disabled", true);
$('button[type="submit"]', form).html('<i class="fa fa-spinner fa-spin"></i> Aguarde, enviando imagens...');
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
alert('sucesso');
form[0].submit();
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
alert('Ocorreu um erro no envio dos arquivos.');
});
this.on("addedfile", function(file) {
// Create the remove button
var removeButton = Dropzone.createElement("<button class='btn red btn-xs btn-block'>Excluir</button>");
// Capture the Dropzone instance as closure.
var _this = this;
// Listen to the click event
removeButton.addEventListener("click", function(e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
_this.removeFile(file);
// If you want to the delete the file on the server as well,
// you can do the AJAX request here.
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
}
}
}
};
}();
<form role="form" action="{$endereco}/galerias/adicionar" id="my-dropzone" class="dropzone form-horizontal" method="post" enctype="multipart/form-data">
<input type="hidden" name="gal_id" value="{$galeria.gal_id}">
<div class="form-body">
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
Você tem alguns erros no formulário. Por favor, verifique abaixo.
</div>
<div class="alert alert-success display-hide">
<button class="close" data-close="alert"></button>
O formulário foi validado com sucesso! Aguarde.
</div>
<div class="form-group">
<label class="control-label col-md-3">Ativo</label>
<div class="col-md-9">
<input type="checkbox" name="active" value="1" class="make-switch" data-on-color="success" data-off-color="danger" data-on-text="SIM" data-off-text="NÃO" {if $galeria.gal_active == 1 or !$livre}checked{/if}>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Título <span class="required"> * </span></label>
<div class="col-md-9">
<input type="text" name="title" placeholder="Título" class="form-control required" minlength="2" maxlength="100" value="{$galeria.gal_title}">
</div>
</div>
<h3 class="form-section">Imagens</h3>
<div class="dropzone-previews">
<h4 style="margin-top: 0;">
<i><strong>Arraste e solte ou clique aqui</strong> para enviar os arquivos</i>
<br><small>Formatos aceitos: JPG e PNG - Tamanho máximo: 5mb - Máximo de 500 arquivos</small>
</h4>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green-meadow">{if !$livre}Adicionar{else}Salvar{/if}</button>
<a href="{$endereco}/galerias/listar" class="btn default">Cancelar</a>
</div>
</div>
</div>
</form>
The error is probably in this code snippet:
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
When submitting the form, it should first be validated, and after being validated start uploading the files with Dropzone.js.