I tend to implement Bootstrap > Documentation > Components > Forms > Validation but feel it makes sense to use jQuery since it is required by many Bootstrap components 🤷♂️
Code to replace provided example…
$('.needs-validation').submit(function(event) {
if ($(this)[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
$(this).addClass('was-validated');
$('.form-control:invalid')[0].focus();
});
Note: That last line focuses on the first invalid field 😉
Original Bootstrap Javacript example…
(function() {
'use strict';
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation');
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);
})();
Suggestions or improvements? Comment below 😊