skip to Main Content

I’m working on the form of website. I’m getting user id, topic, body from user in a form. I’m using bootstrap to validate topic with at least one non white space character. The body should have at least 12 characters excluding leading and trailing white spaces. It prints error message when user does not meet the requirements. However, I cannot get the body to have at least 12 characters.

(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>

2

Answers


  1. Chosen as BEST ANSWER

    I solved the problem by adding a function to check if the textarea input has greater than 12 characters, excluding leading and trailing white spaces

    //validates contact form
    (function () {
      "use strict";
    
      var form = document.querySelector(".needs-validation");
      var textarea = document.getElementById("body");
    
      form.addEventListener(
        "submit",
        function (event) {
          if (!form.checkValidity() || !isValidInput(textarea.value)) {
            event.preventDefault();
            event.stopPropagation();
          }
    
          form.classList.add("was-validated");
        },
        false
      );
      //set textarea validity based on input
      textarea.addEventListener("input", function () {
        if (isValidInput(this.value)) {
          this.setCustomValidity("");
        } else {
          this.setCustomValidity("Invalid input");
        }
      });
      //ensure body is at least 12 characters
      function isValidInput(value) {
        return value.trim().length >= 12;
      }
    })();
    <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">body requires at least 12 characters</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>


  2. Adding a minLength attribute on the textarea with a value of 12 (or a desired value) solves your issue.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search