How do I hook into the validation API to prevent submission until valid?
Asked on Jul 16, 2025
Answer
To prevent form submission until it is valid using Bootstrap 5's validation API, you can use JavaScript to check the form's validity and prevent submission if it is invalid. Here's a simple example to demonstrate this.
<!-- BEGIN COPY / PASTE -->
<form id="myForm" class="needs-validation" novalidate>
<div class="mb-3">
<label for="exampleInput" class="form-label">Example input</label>
<input type="text" class="form-control" id="exampleInput" required>
<div class="invalid-feedback">
Please provide a valid input.
</div>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
<script>
(function () {
'use strict';
var form = document.getElementById('myForm');
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
})();
</script>
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with Bootstrap 5 best practices.- The `novalidate` attribute is used to disable the browser's default validation.
- The `needs-validation` class is used to apply Bootstrap's custom validation styles.
- JavaScript checks the form's validity using `checkValidity()`.
- If the form is invalid, `event.preventDefault()` and `event.stopPropagation()` prevent form submission.
- The `was-validated` class is added to show validation feedback.
Recommended Links:
← Back to All Questions