Skip to content
Advertisement

How to disable bootstrap 4 validation style from valid controls

I’m using bootstrap 4 styling for my application. Application has two text boxes and one submit button. When you click the “Save” button it will call a web API and get some details asynchronously(it will not redirect the page). Validation applied for the first text box only.

(function() {
  'use strict';
  window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
<!DOCTYPE html>
<html>

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <title>Test Page</title>
</head>

<body>
  <form class="container needs-validation" novalidate>
    <div class="form-group row mt-5">
      <label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Name</label>
      <div class="col-sm-10">
        <input type="tel" class="form-control" placeholder="Please enter your name" required />
        <div class="invalid-feedback">
          Please enter the name.
        </div>
      </div>
    </div>
    <div class="form-group row mt-5">
      <label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Address:</label>
      <div class="col-sm-10">
        <input type="tel" class="form-control" />
      </div>
    </div>
    <div class="form-group row">
      <input type="submit" class="btn btn-primary" style="width: 100px;" value="Save" />
    </div>
  </form>
</body>

</html>

My problem:

When I click the “Save” button without entering any values to the text boxes, green color style(validation true style) is applying to the “Address” textbox. I don’t wont that to happen.

I only need red color style(validation failed style) to be applied if the validation is failed. If the values are entered(validation is true), I don’t need any styling to be applied to the text boxes.

Also when I enter some value to the “Name” text box and click the “Save” button, I don’t want green color styling for that text box.

Screenshot:

Screenshot

Advertisement

Answer

I, for one, do not like overriding the CSS style so you could also choose to just specify which fields to validate instead of the entire form.

Add a class to your .form-group element (e.g. .validate-me)

    <form class="container needs-validation" novalidate>
        <div class="form-group row mt-5 validate-me">
            <label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Name</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" placeholder="Please enter your name" required />
                <div class="invalid-feedback">
                    Please enter the name.
                </div>
            </div>
        </div>
        <div class="form-group row mt-5">
            <label for="txtSessionDescription" class="col-2 col-md-2 col-sm-2 col-form-label">Address:</label>
            <div class="col-sm-10">
                <input type="tel" class="form-control" formnovalidate="formnovalidate" id="address" />
            </div>
        </div>
        <div class="form-group row">
            <input type="submit" class="btn btn-primary" style="width: 100px;" value="Save"/>
        </div>
    </form>

Now change your JavaScript slightly, retrieve all the form-groups with the validate-me class and instead of calling form.classList.add('was-validated') loop through all the captured form-groups and add was-validated to them instead.

window.addEventListener('load', function () {
                // Fetch all the forms we want to apply custom Bootstrap validation styles to
                var forms = document.getElementsByClassName('needs-validation');

                // Get all form-groups in need of validation
                var validateGroup = document.getElementsByClassName('validate-me');

                // Loop over them and prevent submission
                var validation = Array.prototype.filter.call(forms, function (form) {
                    form.addEventListener('submit', function (event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        }

                        //Added validation class to all form-groups in need of validation
                        for (var i = 0; i < validateGroup.length; i++) {
                            validateGroup[i].classList.add('was-validated');
                        }
                    }, false);
                });
            }, false);
Advertisement