简体   繁体   English

带有jquery validate和ajax post表单的验证表单空白textarea中的错误

[英]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: 在我的jsp页面中,具有文件funcoes.js的脚本链接,而funcoes.js具有ajax函数,用于在提交表单后插入注释:

$("#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: 我的JSP页面在关闭html标记正文之后有jquery验证代码:

<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. 问题是,当我尝试发布5个字母以下或空白jquery的新评论时,会显示该消息,但是如果我提交表单代码,则会注册一个新评论。 I wonder how I do to validate jquery ajax not working before to leave comments User registering with less than 5 letters or blanks. 我想知道如何做才能验证jquery ajax在发表评论之前不起作用用户注册少于5个字母或空格。 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. 您应该将ajax代码放在submitHandler .validate()方法的submitHandler回调函数中, 而不是放在自己的.submit()处理程序中。

$(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. submitHandler :当表单有效时用于处理实际提交的回调。 Gets the form as the only argument. 获取表单作为唯一参数。 Replaces the default submit. 替换默认的提交。 The right place to submit a form via Ajax after it is validated. 验证后通过Ajax提交表单的正确位置


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. 由于您已经在.validate()方法中指定了required: true ,因此在相应的元素上不需要required="required"属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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