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

Bootstrap表单验证失效排查:为何表单无校验直接提交?

Bootstrap表单验证失效的原因及解决办法

你的表单验证失效主要有三个问题,逐个解决即可恢复正常:

1. 重复引入Bootstrap JS文件导致冲突

你在BaseTemplate中先引入了bootstrap.bundle.min.js——这个文件已经包含了Popper.js和Bootstrap核心JS功能,但后面又重复引入了单独的Popper.js和bootstrap.min.js,这会造成JS代码冲突,直接破坏验证逻辑。

解决方法:删除</body>前的两个重复script标签,只保留头部的bootstrap.bundle.min.js即可。修改后的BaseTemplate脚本部分如下:

<!-- 仅保留这一个Bootstrap JS文件 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>

2. 缺少触发验证的自定义JS代码

Bootstrap 5的表单验证不会自动触发,必须手动添加JS监听表单提交事件,阻止默认提交并触发验证样式。

解决方法:在form.ejs的表单末尾添加以下JS代码:

<script>
(function () {
  'use strict'

  const forms = document.querySelectorAll('.needs-validation')

  Array.from(forms).forEach(form => {
    form.addEventListener('submit', event => {
      if (!form.checkValidity()) {
        event.preventDefault()
        event.stopPropagation()
      }
      form.classList.add('was-validated')
    }, false)
  })
})()
</script>

3. 标签类名拼写错误

你代码中的form-lable是拼写错误,正确的类名应为form-label,这个错误会导致标签样式异常,也间接影响验证提示的显示。

解决方法:将所有<label>标签的class="form-lable"修改为class="form-label"。

修改后的完整form.ejs代码

<% layout('BaseTemplate') %>

<h1 class="mb-5 offset-5">New product</h1>

<form action="/product" method="post" class="w-50 offset-3 needs-validation" novalidate>
    <label for="name" class="form-label mb-1">Name</label>
    <input type="text" id="name" name="name" class="form-control mb-3" required>
    <label for="price" class="form-label mb-1">Price</label>
    <input type="number" id="price" name="price" class="form-control mb-3" required>
    <label for="description" class="form-label mb-1">Description</label>
    <input type="text" id="description" name="description" class="form-control mb-3" required>
    <label for="image" class="form-label mb-1">Image</label>
    <input type="text" id="image" name="image" class="form-control mb-3" required>
    <button type="submit" class="btn btn-outline-info">Submit</button>
</form>

<script>
(function () {
  'use strict'

  const forms = document.querySelectorAll('.needs-validation')

  Array.from(forms).forEach(form => {
    form.addEventListener('submit', event => {
      if (!form.checkValidity()) {
        event.preventDefault()
        event.stopPropagation()
      }
      form.classList.add('was-validated')
    }, false)
  })
})()
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:45:48