如何验证使用Dropzone.js的表单?

时间:2015-05-12 17:09:58

标签: javascript jquery jquery-validate dropzone.js

我想在发送文件之前验证我的表单。我有这个HTML代码:

<form role="form" action="#" 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">
            <i class="fa fa-cloud-upload fa-3x pull-left hidden-xs hidden-sm"></i>
            <div class="pull-left">
                <h4 style="margin-top: -10px;">
                                        <strong>Arraste e solte ou clique aqui para enviar os arquivos</strong>
                                        <br><small>Formatos aceitos: JPG e PNG - Tamanho máximo: 5mb - Máximo de 500 arquivos</small>
                                    </h4>
            </div>
            <div class="clearfix"></div>
        </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>

这是我的JS代码:

var Galerias = function() {
    return {
        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...');
                }

            });

        },

        initDropzone: function() {
            Dropzone.options.myDropzone = {
                url: endereco + '/src/galerias/upload.php',
                previewsContainer: ".dropzone-previews",
                clickable: ".dropzone-previews",
                acceptedFiles: 'image/*',
                autoProcessQueue: false,
                uploadMultiple: false,
                parallelUploads: 500,
                maxFiles: 500,
                maxFilesize: 5, // mb
                paramName: "file",
                init: function() {
                    var myDropzone = this;
                    $.get(endereco + '/src/galerias/getpics.php', function(data) {
                        $.each(data, function(key, value) {
                            var file = {
                                serverId: value.name,
                                size: value.size
                            };
                            myDropzone.options.addedfile.call(myDropzone, file);
                            myDropzone.options.thumbnail.call(myDropzone, file, galerias + "/galerias/" + value.name);
                        });
                    });
                    this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
                        initForm();
                        e.preventDefault();
                        e.stopPropagation();
                        myDropzone.processQueue();
                    });

                    this.on("sending", function() {
                        $('button[type="submit"]').prop("disabled", true);
                        $('button[type="submit"]').html('<i class="fa fa-spinner fa-spin"></i> Aguarde, enviando imagens...');
                    });
                    this.on("error", function(files, response) {
                        alert('Ocorreu um erro no envio dos arquivos.');
                    });
                    this.on("maxfilesexceeded", function(file) {
                        alert("O limite máximo de arquivos foi excedido.");
                    });
                    this.on("complete", function(file) {
                        if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
                            window.location.href = endereco + '/galerias/listar';
                        }
                    });
                    this.on("addedfile", function(file) {
                        var removeButton = Dropzone.createElement("<button class='btn red btn-xs btn-block'>Excluir</button>");

                        var _this = this;

                        removeButton.addEventListener("click", function(e) {
                            e.preventDefault();
                            e.stopPropagation();

                            _this.removeFile(file);
                        });

                        file.previewElement.appendChild(removeButton);
                    });
                }
            }
        }
    };
}();

单击提交按钮时,表单将通过此行中包含的 initForm(); 函数进行验证:

this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
    initForm();
    e.preventDefault();
    e.stopPropagation();
    myDropzone.processQueue();
});

这就是问题所在!表格经过验证:好的!但是现在我需要在验证表单后,它返回到使文件上传的函数。

在验证表格后,如果有文件要发送,也需要提交。

我该怎么做? 谢谢你们!

0 个答案:

没有答案