My Boostrap 5 Validation is not working. Even though I did what is said in the Boostrap 5 validation documentation.
Actually you need to include the javascript code below the form.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<html> <head> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> </head> <body> <main role="main"> <div class="container mt-5 py-5 rounded bg-light"> <form class="needs-validation" novalidate> <div class="row"> <div class="col-sm-6"> <div class="input-group mb-3"> <span class="input-group-text title" for="validationDefault01">Product #</span> <input type="text" class="form-control" id="inputNum" required> <div class="invalid-feedback">Please enter a product number</div> </div> </div> <div class="col-sm-6"> <div class="input-group mb-3"> <span class="input-group-text title" for="inputName">Product name</span> <input type="text" class="form-control" id="inputName" required> <div class="invalid-feedback">Please enter a product name</div> </div> </div> </div> <div class="btn-group float-end" role="group"> <button id="myButton" type="submit" class="btn btn-sm btn-outline-secondary">Submit</button> </div> </form> </div> </main> <!-- Validation script must be below the form --> <script> (function () { 'use strict' // 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) { if (!form.checkValidity()) { event.preventDefault() event.stopPropagation() } form.classList.add('was-validated') }, false) }) })() </script> </body> </html> |