<form class="needs-validation" novalidate> <div class="mb-3"> <label for="emailInput" class="form-label">Email address</label> <input type="email" class="form-control" id="emailInput" required> <div class="invalid-feedback"> Please provide a valid email. </div> </div> <button class="btn btn-primary" type="submit">Submit</button> </form> <script> (() => { 'use strict' const form = document.querySelector('.needs-validation') form.addEventListener('submit', event => { if (!form.checkValidity()) { event.preventDefault() event.stopPropagation() } form.classList.add('was-validated') }, false) })()
When the form is submitted with an empty required email input, checkValidity() returns false. The script prevents submission and adds the was-validated class. Bootstrap styles the input border red and shows the invalid-feedback message.
Bootstrap styles invalid inputs only when the form has the was-validated class. The selector .was-validated .form-control:invalid applies red borders and shows feedback messages.
<input type="text" class="form-control is-valid" aria-describedby="validFeedback"> <div id="validFeedback" class="valid-feedback"> Looks good! </div>
The is-valid class styles the input border green. The valid-feedback message is shown by default when this class is present.
The aria-describedby attribute on the input points to the ID of the validation message. This helps screen readers read the message when the input is focused.
form.addEventListener('submit', event => { if (!form.checkValidity()) { event.preventDefault() event.stopPropagation() } form.classList.add('was-validated') }, false)
The event.preventDefault() method stops the browser from submitting the form if the inputs are invalid. The checkValidity() method returns false when inputs fail validation.