You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

禁用表单重复提交的代码为何无法生效?

Bootstrap 结账表单:自定义验证 + 原生JS防止重复提交

我最近在自己的项目里做了个结账表单,用Bootstrap实现自定义验证,同时用原生JS解决了表单验证通过后重复提交的问题——毕竟用户手抖点两次提交的情况太常见了!下面是我的实现方案,参考了SO上常用的禁用提交思路,但完全用原生JS写的,不用依赖jQuery。

一、HTML 表单结构(带Bootstrap验证标记)

首先是表单的基础结构,要加上Bootstrap的验证相关类,比如needs-validation,还有novalidate属性来禁用浏览器默认验证:

<form id="checkoutForm" class="needs-validation" novalidate>
  <!-- 结账表单字段示例 -->
  <div class="mb-3">
    <label for="email" class="form-label">邮箱</label>
    <input type="email" class="form-control" id="email" required>
    <div class="invalid-feedback">请输入有效的邮箱地址</div>
  </div>
  <div class="mb-3">
    <label for="cardNumber" class="form-label">卡号</label>
    <input type="text" class="form-control" id="cardNumber" required pattern="[0-9]{16}">
    <div class="invalid-feedback">请输入16位有效卡号</div>
  </div>
  <!-- 更多表单字段... -->
  <button type="submit" class="btn btn-primary" id="submitBtn">提交订单</button>
</form>

二、原生JS 实现验证+防重复提交

下面是核心的submitForm函数,我把Bootstrap的自定义验证和防重复提交逻辑整合在一起了:

function submitForm() {
  // 获取所有需要应用Bootstrap自定义验证样式的表单
  const forms = document.getElementsByClassName('needs-validation');
  
  // 遍历表单,绑定提交事件
  Array.prototype.filter.call(forms, function(form) {
    form.addEventListener('submit', function(event) {
      // 阻止表单默认提交行为
      event.preventDefault();
      event.stopPropagation();
      
      // 触发Bootstrap的验证
      form.classList.add('was-validated');
      
      // 检查表单是否验证通过
      if (form.checkValidity()) {
        const submitBtn = document.getElementById('submitBtn');
        // 禁用提交按钮,防止重复点击
        submitBtn.disabled = true;
        // 修改按钮文本,给用户反馈
        submitBtn.textContent = '提交中...';
        
        // 这里写表单提交的逻辑,比如发送AJAX请求
        fetch('/api/checkout', {
          method: 'POST',
          body: new FormData(form)
        })
        .then(response => response.json())
        .then(data => {
          // 提交成功后的处理,比如跳转成功页
          window.location.href = '/success';
        })
        .catch(error => {
          // 提交失败,恢复按钮状态
          submitBtn.disabled = false;
          submitBtn.textContent = '提交订单';
          alert('提交失败,请重试');
          console.error('Error:', error);
        });
      }
    }, false);
  });
}

// 页面加载完成后初始化函数
document.addEventListener('DOMContentLoaded', submitForm);

三、关键逻辑说明

  • Bootstrap自定义验证:通过给表单添加was-validated类触发验证样式,checkValidity()方法检查表单是否符合验证规则,不符合的话会显示我们定义的invalid-feedback提示。
  • 防重复提交核心:当表单验证通过后,立刻禁用提交按钮并修改按钮文本,避免用户重复点击;如果提交失败(比如网络问题),要记得恢复按钮的可点击状态,不然用户没法重试。
  • 原生JS实现:完全用原生的document方法和fetch API,不需要引入jQuery,轻量又高效。

这个方案我在项目里用了挺久的,没出现过重复提交的问题,Bootstrap的验证样式也很贴合项目风格,推荐给有需要的朋友!

内容的提问来源于stack exchange,提问作者tagurit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:42:40