1

我有一些带有 jquery 验证的表单,我想div在表单上方的同一元素中显示所有错误。

我尝试这样做,但不工作:

$("#contactForm").validate({
            rules: {
                assunto: { required: true },
                nome: { required: true, minlength: 2 }, 
                email: { required: true, email: true },
                telefone: { required: true },
                mensagem: { required: true }
            }, 
            errorPlacement: function(error, element) {
                if (element.attr("name") == "assunto" || element.attr("name") == "nome" || element.attr("name") == "email" || element.attr("name") == "telefone" || element.attr("name") == "mensagem" )
                //here i think i want to insert the location but i don't know how!
            else
                //here i think i want to insert the location but i don't know how!
            },

            messages: { 
                assunto: {required: 'É necessário escolher um assunto'},
                nome: { required: 'É necessário preencher o campo nome', minlength: 'No mínimo 2 letras' }, 
                email: { required: 'Informe seu email', email: 'Informe um Email válido' },             
                telefone: { required: 'Informe seu Telefone' },
                mensagem: { required: 'Escreva sua Mensagem' }
            },

            submitHandler: function(form){
                var dados = $( form ).serialize();  
                $.ajax({  
                    type: "POST",  
                    url: "enviafaleconosco.asp",
                    data: dados,  
                    success: function( data )  
                    {  
                        alert("Obrigado! Seu contato foi enviado com sucesso. Breve retornaremos!");
                        $("#contactForm")[0].reset();                   
                    }  
                });  
                return false;  
            }           
    });

我做错了什么?

4

1 回答 1

2

你在这里有一个语法错误:

errorPlacement: function(error, element) {
                if (element.attr("name") == "assunto" || element.attr("name") == "nome" || element.attr("name") == "email" || element.attr("name") == "telefone" || element.attr("name") == "mensagem" )
                //here i think i want to insert the location but i don't know how!
                else
                //here i think i want to insert the location but i don't know how!
            },

如果 if 和 else 里面没有任何内容,则必须添加大括号{}来关闭它们:

errorPlacement: function(error, element) {
                if (element.attr("name") == "assunto" || element.attr("name") == "nome" || element.attr("name") == "email" || element.attr("name") == "telefone" || element.attr("name") == "mensagem" ){
                //here i think i want to insert the location but i don't know how!
                } else {
                //here i think i want to insert the location but i don't know how!
                }
            },

始终将花括号添加到 if 块也是一个好习惯,即使它们是单行的

于 2013-01-03T19:56:41.427 回答