简体   繁体   中英

Error in the validation form blank textarea with jquery validate and ajax post form

I have a spring project and a task to register a comment on a particular system design. The form of the page is as follows:

<form id="formularioCadastroComentario" role="form" method="POST" class="form-horizontal">
    <input type="hidden" id="projeto" name="projeto" value="${projeto.id}"> <input type="hidden" id="usuario" name="usuario" value="${usuario.id}">
    <input type="hidden" id="usuario_nome" name="usuario" value="${usuario.nome}"> <label class="control-label"for="textocomentarioInput"><h3>Novo Comentário</h3></label>
            <div class="form-group">
                <div class="input-group">
                    <textarea id="textocomentarioInput" name="texto" class="form-control" placeholder="Comentário" required="required"></textarea>
                </div>
            </div>
    <br> <input name="botao" id="botaoEnviarComentario" class="btn btn-primary" value="Enviar" /> 
    <a href="<c:url value="/projeto/index"></c:url>" class="btn btn-default">Voltar</a>
</form>

In my jsp page has the script link for the file funcoes.js, and the funcoes.js has the ajax function for insert a comment after a submit the form:

$("#formularioCadastroComentario").submit(function(e) {
    var idProjeto = $('#projeto').val();
    var idUsuario = $('#usuario').val();
    var nomeUsuario = $('#usuario_nome').val();
    var cabecalho = "Comentários do Projeto";
    var textoComentario = $('#textocomentarioInput').val();
    var data = new Date();
    var dataFormatada = ("0" + data.getDate()).substr(-2)+ "-" + ("0" +(data.getMonth()+ 1)).substr(-2)+ "-"+ data.getFullYear()+ " "+ ('0' + data.getHours()).slice(-2)+ ":"+ ('0' + data.getMinutes()).slice(-2);
    $.ajax({
     type : "POST",
     data : {
        idProjeto : idProjeto,
        idUsuario : idUsuario,
        texto : textoComentario
        },
     url : "/gpa-pesquisa/comentario/comentarProjeto",
     dataType : "html",
     success : function() {
        $('#comentarioList').prepend(
            '<li class="well">'
            + '<div class="nome_usuario">'
            + nomeUsuario+ '</div>'
            + '<div class="corpo_texto">'
            + textoComentario + '</div>'
            + '<div class="formatacao_data">'
            + dataFormatada + '</div>'
            + '</li>');
        $("#headComentarios").show();
        }
    });
 $("#formularioCadastroComentario")[0].reset();
});

Im my JSP page has the jquery validate code after the close html tag body:

<script type="text/javascript">
$(document).ready(function($) {
    $("#formularioCadastroComentario").validate({
        rules : {
            texto : {
                minlength : 5,
                required : true,
            }
        },
        messages : {
            texto : {
                required : "Campo obrigatório",
                minlength : "O campo deve ter no mínimo 5 caracteres"
            }
        },
        highlight : function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        unhighlight : function(element) {
            $(element).closest('.form-group').removeClass('has-error');
        },
        errorElement : 'span',
        errorClass : 'help-block',
        errorPlacement : function(error, element) {
            if (element.parent('.input-group').length) {
                error.insertAfter(element.parent());
            } else {
                error.insertAfter(element);
            }
        }
    });
});

The problem is that when I try to post a new comment under 5 letters or with blanks jquery validate the message appears, but if I submit the form code makes registering a new comment. I wonder how I do to validate jquery ajax not working before to leave comments User registering with less than 5 letters or blanks. Thank you,

You're supposed to put the ajax code within the submitHandler callback function of the .validate() method, not within your own .submit() handler.

$(document).ready(function($) {
    $("#formularioCadastroComentario").validate({
        submitHandler: function(form) {
            var idProjeto = $('#projeto').val();
            // the rest of your ajax function...
            ....
            return false;  // block the default submit
        },
        rules : {
            texto : {
                minlength : 5,
                required : true,
            }
        },
        ......

Documentation :

submitHandler : Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated.


BTW, you don't need to declare your rules in two places. Since you already have required: true specified within the .validate() method, you will not need the required="required" attribute on the corresponding elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM