我打开一个jQuery对话框,其中包含一个表单,该表单由打开对话框时触发的ajax调用加载。当用户单击“确定”时,我想在使用ajax提交表单之前验证表单。 以下是分配给“确定”按钮的回调:
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");
}
};
我已将代码基于this question但我无法弄清楚如何在执行ajax提交时触发客户端验证。
我正在使用jquery-1.9.1,jquery.unobtrusive-ajax,jquery.validate和jquery.form
答案 0 :(得分:2)
您需要检查插件方法valid的值,这样您就需要
if ($form.valid())
{
// do stuff
}
不是这个
if ($form.valid)
{
// always true, as presence of the plugin method is 'truthy'
}