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

如何用Bootstrap验证表单textarea去除首尾空格后至少12字符?

修复Bootstrap表单正文的自定义长度验证问题

问题说明

开发表单时需收集用户ID、主题、正文内容:

  • 主题已通过Bootstrap原生验证实现「至少包含一个非空白字符」的要求
  • 正文要求去除首尾空格后至少12个字符,但现有代码无法实现该验证逻辑,提交时无法正确触发错误提示

问题根源

原代码仅在提交时判断长度并阻止提交,但未利用Bootstrap表单验证的setCustomValidity API标记textarea的无效状态,导致Bootstrap无法识别自定义验证规则,也就不会显示错误提示。

修复方案

通过JavaScript的setCustomValidity方法为textarea设置自定义验证规则,让Bootstrap的表单验证系统能够识别并展示错误提示:

修改后的完整代码

HTML部分

<html>
<head>
<meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
      crossorigin="anonymous"
    />
</head>
<body>

<div class="container">
  <form class="needs-validation" novalidate action="">
    <div class="mb-3">
      <label for="id" class="col-form-label">用户ID</label>
      <input
        type="text"
        class="form-control"
        id="id"
        placeholder="用户ID..."
        maxlength="15"
      />
    </div>
    <div class="mb-3">
      <label for="topic" class="col-form-label">主题</label>
      <input
        type="text"
        class="form-control"
        id="topic"
        placeholder="请输入主题..."
        required
        pattern=".*\S+.*"
      />
      <div class="invalid-feedback">
        请输入至少一个非空白字符
      </div>
    </div>
    <div class="mb-3">
      <label for="body" class="col-form-label">正文</label>
      <textarea
        class="form-control"
        id="body"
        placeholder="请输入正文内容..."
        rows="10"
        required
      ></textarea>
      <div class="invalid-feedback"></div>
    </div>
    <button type="submit" class="btn btn-primary">提交</button>
  </form>
</div>
<script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
      crossorigin="anonymous"
    ></script>
    </body>
    </html>

JavaScript部分

(function () {
  // 获取所有需要验证的表单
  var forms = document.querySelectorAll(".needs-validation");

  // 遍历表单并绑定提交事件
  Array.prototype.slice.call(forms).forEach(function (form) {
    form.addEventListener(
      "submit",
      function (event) {
        var bodyField = document.getElementById("body");
        var minRequiredLength = 12;
        var trimmedContentLength = bodyField.value.trim().length;

        // 设置自定义验证规则
        if (trimmedContentLength < minRequiredLength) {
          bodyField.setCustomValidity(`正文去除首尾空格后至少需要${minRequiredLength}个字符`);
        } else {
          // 清除验证错误
          bodyField.setCustomValidity("");
        }

        // 执行表单验证,若无效则阻止提交
        if (!form.checkValidity()) {
          event.preventDefault();
          event.stopPropagation();
        }

        // 添加验证状态类,触发Bootstrap样式
        form.classList.add("was-validated");
      },
      false
    );
  });
})();

关键修改点

  1. 移除了单独的错误提示文本设置,改用setCustomValidity直接为textarea元素绑定验证消息,Bootstrap会自动将该消息显示在对应的invalid-feedback容器中
  2. 调整验证逻辑:先判断正文长度并设置验证状态,再调用form.checkValidity()让Bootstrap统一处理所有验证规则
  3. 当正文长度符合要求时,必须调用setCustomValidity("")清除之前的错误状态,否则表单会一直被判定为无效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 14:49:53