在完成表单校验后禁用提交按钮

编程语言 2026-07-12

我在ASP.NET MVC表单中使用jQuery.Validation(jQuery验证插件),希望在jQuery验证通过且表单实际提交时禁用提交按钮。验证是在后台触发的(我没有手动执行)。

现在我是通过在我的 <form> 语句中放置一个 onsubmit 命令来禁用提交按钮。

@using (Html.BeginForm("NewApplication", "AppController", FormMethod.Post, new { id = "AppForm", onsubmit = "this.CreateButton.disabled = true;" }))
{ }

接着我有一个jQuery语句来检测提交是否被按下,我手动调用验证以查看它是否失败;如果失败,我会重新启用提交按钮,让用户在修正无效项后可以继续点击。

$("#CreateButton").click(function () {
     if ($('#AppForm').valid()) {
         // validation passed
     } else {
         // validation failed
         $("#CreateButton").prop("disabled", false);
         return false;
     }

     return true;
});

虽然这确实起作用,我在上面的jQuery片段中手动调用了验证,随后它在后台又自动运行了一次。

是否有更好的方法来检查自动验证是否通过,然后再禁用我的提交按钮?

解决方案

是的,你可以通过将事件处理程序绑定到你的表单来实现,该处理程序跟踪在 <input> 字段上的 keyupblurchange 事件。

在事件处理程序中,它将验证整个表单,并根据表单是否有效来设置按钮的启用/禁用。之所以使用 validator.checkForm() 而不是 form.valid(),是因为这会对所有表单字段触发验证,即使字段尚未填写,也会显示错误信息。

var form = $('#AppForm');
var validator = form.data('validator');

form.on('keyup blur change', "input", function () {
  // validate only current field
  validator.element(this);

  // Check form valid status without firing the validations for all fields
  var isFormValid = validator.checkForm();

  $('#CreateButton').prop('disabled', !isFormValid);
});

并默认禁用提交按钮。

@using (Html.BeginForm("NewApplication", "AppController", FormMethod.Post, new { id = "AppForm" }))
{
    ...

    <button type="submit" id="CreateButton" class="btn btn-success submit" disabled>Create</button>
}

Sample MVC Demo @ .NET Fiddle

备选方案1

我觉得这应该是一个更好的做法。

Form:
@using (Html.BeginForm("NewApplication", "AppController", FormMethod.Post, new { id = "AppForm" }))
{ 
    <button id="CreateButton" type="submit">Create</button>
}
JS: 
$("#AppForm").on("submit", function () {
    if ($(this).valid()) {
        $("#CreateButton").prop("disabled", true); 
        //Other stuff       
    }else{
        $("#CreateButton").prop("disabled", false);
        //Other stuff
    }
});

不是捕获按钮点击事件。当MVC表单中的提交按钮被点击时,它会自动触发表单提交事件。你可以拦截它,检查表单是否有效并据此采取行动。

备选方案2

实现这一点的另一种方式是在离开此页面(卸载或导航away)时隐藏提交按钮(前提是验证失败已经阻止提交表单)。

window.onbeforeunload = function(e) {
    $('#CreateButton').prop('disabled', true);
};
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章