1

我正在打开一个 jQuery 对话框,其中包含一个由打开对话框时触发的 ajax 调用加载的表单。当用户单击确定时,我想在使用 ajax 提交之前验证表单。这是分配给 OK 按钮的回调:

var dialogOK = function () {
    var $form = $(this).find("form:first");
    if ($form.find("input:first").length > 0) {
        $form.removeData("validator").removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse($form);
        $form.validate({
            submitHandler: function (form) {
                alert("This alert doesn't appear");
            },
            invalidHandler: function (event, validator) {
                alert("Neither does this one");
            }
        });
        if ($form.valid) {
            alert("form.valid says it's valid when it's not");
            //$form.submit(); //when this is called the client-side 
                             //validation works and the form is not submitted
            //but when I call ajaxSubmit (forms jQuery plugin)
            //the form is submitted
            $form.ajaxSubmit({
                success: function () {
                    alert("And I still need to work out how to check whether 
                        server-side validation passed before I close the dialog");
                }
            });
        }

    }
    else {
        $(this).dialog("close");
    }
};

我已经根据这个问题编写了代码,但我不知道如何在进行 ajax 提交时触发客户端验证。

我正在使用 jquery-1.9.1、jquery.unobtrusive-ajax、jquery.validate 和 jquery.form

4

1 回答 1

2

你需要检查插件方法的值是否有效,所以你需要这个

if ($form.valid()) 
{
  // do stuff
}

不是这个

if ($form.valid) 
{
  // always true, as presence of the plugin method is 'truthy'
}
于 2013-06-07T13:21:31.847 回答