为什么jQuery在发送表单后验证运行?

时间:2012-07-31 18:52:05

标签: jquery forms validation

我正在尝试使用jQuery validate插件验证此表单,但是一旦找到错误它就不会停止javascript代码,因此表单将被发送到DB,然后才会显示错误。我该怎样做才能正确地将这些事件联系起来?

$("#salvar-cur").live("click", function () {
    var validator = $("#frm_curriculo").validate({
        rules: {
            cur_nome: {
                required: true
            }
            //other options
        },
        messages: {
            cur_nome: {
                required: "*"
            }
            //other options
        }
    });
    if (validator.numberOfInvalids() == 0) {
        alert("Success!")
        var params = $("#frm_curriculo").serialize();
        $.ajax({
            type: "POST",
            url: "controller/ctrl_curriculo.php",
            data: "acao=inserir&" + params,
            dataType: "html",
            contentType: "application/x-www-form-urlencoded",
            success: function () {
                $("#frm_curriculo")[0].reset();
            }
        });
    }
});

1 个答案:

答案 0 :(得分:1)

首先,您将在每次点击时重新添加验证器。你应该在事件处理程序之外做到这一点。

此外,请检查validator.numberOfInvalids(),而不是检查$("#frm_curriculo").valid(),这将验证表单并返回truefalse

另外请注意,如果#salvar-cur是提交按钮,则您需要阻止其默认操作。

$(function(){
    $("#frm_curriculo").validate({
        rules: {
            cur_nome: {
                required: true
            }
            //other options
        },
        messages: {
            cur_nome: {
                required: "*"
            }
            //other options
        }
    });
});

$("#salvar-cur").live("click", function (e) {
    e.preventDefault();
    if ($("#frm_curriculo").valid()) {
        alert("Success!")
        var params = $("#frm_curriculo").serialize();
        $.ajax({
            type: "POST",
            url: "controller/ctrl_curriculo.php",
            data: "acao=inserir&" + params,
            dataType: "html",
            contentType: "application/x-www-form-urlencoded",
            success: function () {
                $("#frm_curriculo")[0].reset();
            }
        });
    }
});