linuxfront-v2-logistics/js/bootstrap-validation.js
A lightweight, single-purpose script that enhances HTML5 form validation by integrating with Bootstrap’s validation styles. It listens for form submissions, checks validity, prevents invalid submissions, and toggles CSS classes to display validation feedback.
Overview
- ⚙️ Activates on page load
- 📋 Attaches to every
<form>element - 🚫 Prevents invalid form submissions
- ✅ Adds Bootstrap’s
was-validatedclass for styling feedback
Purpose
This script ensures forms use native HTML5 validation and Bootstrap’s visual cues.
It prevents accidental submission of invalid data.
It requires no external libraries beyond Bootstrap’s CSS.
Script Breakdown
1. DOMContentLoaded Listener
Fires when the initial HTML is fully parsed.
Ensures all form elements exist before attaching handlers.
document.addEventListener('DOMContentLoaded', function () {
// …core logic here…
});
2. Selecting All Forms 📋
Uses a CSS selector to gather every <form> on the page.
const forms = document.querySelectorAll('form');
querySelectorAll('form'): returns aNodeListof forms- Converted to an array for iteration
3. Iterating Over Forms
Converts the NodeList into an array and loops through each form.
Array.prototype.slice.call(forms).forEach(function (form) {
// attach submit listener
});
- Ensures compatibility with older browsers lacking
NodeList.forEach
4. Handling the Submit Event
Attaches a submit listener to each form to validate before send.
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
4.1 HTML5 Validation Check
form.checkValidity()returnstrueif all controls are valid- Leverages built-in constraints (e.g.,
required,pattern,minlength)
4.2 Prevent Default & Stop Propagation
event.preventDefault(): blocks form submissionevent.stopPropagation(): stops the event bubbling up
4.3 Adding Bootstrap Feedback Class
form.classList.add('was-validated')
Triggers Bootstrap’s validation styling:.is-valid&.is-invalidon form controls- Displays
.valid-feedback/.invalid-feedbackelements
Key Methods & Properties
| Method / Property | Purpose |
|---|---|
| document.addEventListener | Listens to global DOM events |
| querySelectorAll('form') | Selects all form elements |
| Array.prototype.slice.call(forms) | Converts NodeList to Array |
| form.addEventListener('submit',…) | Hooks into form submission |
| form.checkValidity() | Native HTML5 validation check |
| event.preventDefault() | Stops the browser’s default submit behavior |
| event.stopPropagation() | Prevents event bubbling |
| form.classList.add('was-validated') | Applies Bootstrap validation feedback styles |
Integration Guide
- Include Bootstrap’s CSS in
<head>:<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> - Place this script after your forms, before
</body>:<script src="js/bootstrap-validation.js"></script> - Mark up your form with validation classes:
<form class="needs-validation" novalidate> <div class="mb-3"> <label for="email" class="form-label">Email</label> <input type="email" class="form-control" id="email" required> <div class="invalid-feedback">Please enter a valid email.</div> </div> <button class="btn btn-primary" type="submit">Submit</button> </form>
Browser Compatibility
- Modern browsers with support for:
- HTML5 form validation (
checkValidity()) classListAPIDOMContentLoadedevent
- HTML5 form validation (
- Falls back gracefully (no errors) on older browsers without full styling
Best Practices
- Always include
novalidateon forms to suppress native tooltips. - Use descriptive feedback text within
.valid-feedback/.invalid-feedback. - Combine with server-side validation for security and data integrity.
- Keep forms simple; avoid overly complex nested validations.
Happy validating! 🎉