如何使用 bootstrap 验证表单文本区域至少有 12 个字符?

问题描述 投票:0回答:1

我正在制作网站的形式。我以表单形式从用户那里获取用户 ID、主题、正文。我正在使用引导程序来验证至少包含一个非空白字符的主题。正文应至少包含 12 个字符(不包括前导空格和尾随空格)。当用户不满足要求时,它会打印错误消息。但是,我无法让正文至少有 12 个字符。

(function () {
  // Fetch all the forms we want to apply custom Bootstrap validation styles to
  var forms = document.querySelectorAll(".needs-validation");

  // Loop over them and prevent submission
  Array.prototype.slice.call(forms).forEach(function (form) {
    form.addEventListener(
      "submit",
      function (event) {
        var feedback = document.getElementById("customvalidation");
        var body = document.getElementById("body");
        var min_text = 12;
        //trim leading and trailing white space
        var length = body.value.trim().length;

        if (!form.checkValidity() || length < min_text) {          
          feedback.textContent = `body requires minimum ${min_text} characters`;
          event.preventDefault();
          event.stopPropagation();
        }

        form.classList.add("was-validated");
      },
      false
    );
  });
})();
<html>
<head>
<meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/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">User ID</label>
      <input
        type="text"
        class="form-control"
        id="id"
        placeholder="User ID..."
        maxlength="15"
      />
    </div>
    <div class="mb-3">
      <label for="topic" class="col-form-label">Topic</label>
      <input
        type="text"
        class="form-control"
        id="topic"
        placeholder="What is it about..."
        required
        pattern=".*\S+.*"
      />
      <div class="invalid-feedback">
        input at least one non white space character
      </div>
    </div>
    <div class="mb-3">
      <label for="body" class="col-form-label">Body</label>
      <textarea
        class="form-control"
        id="body"
        placeholder="Write something..."
        rows="10"
        required
      ></textarea>
      <div class="invalid-feedback" id="customvalidation"></div>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
</div>
<script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
      crossorigin="anonymous"
    ></script>
    </body>
    </html>

javascript html bootstrap-5
1个回答
0
投票

在文本区域上添加值为

minLength
(或所需值)的
12
属性可以解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.