Ask any question about Bootstrap here... and get an instant response.
Post this Question & Answer:
How to implement both client-side and server-side validation for a Bootstrap form without duplicating error messages?
Asked on Dec 29, 2025
Answer
To implement both client-side and server-side validation in a Bootstrap form without duplicating error messages, you can use Bootstrap's validation classes for client-side validation and handle server-side validation by adding error messages dynamically. Here's a simple example:
<!-- BEGIN COPY / PASTE -->
<form id="myForm" class="needs-validation" novalidate>
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" required>
<div class="invalid-feedback">
Please enter a valid email.
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
// Client-side validation
(function () {
'use strict';
var forms = document.querySelectorAll('.needs-validation');
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);
});
})();
// Example server-side validation
document.getElementById('myForm').addEventListener('submit', function (event) {
event.preventDefault(); // Remove this line in production
var emailInput = document.getElementById('email');
var serverError = false; // Simulate server-side error
if (serverError) {
emailInput.classList.add('is-invalid');
emailInput.nextElementSibling.textContent = 'Server-side error: Email already exists.';
}
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with Bootstrap 5 best practices.- The `novalidate` attribute disables the browser's default validation, allowing custom handling.
- The `needs-validation` class is used to apply Bootstrap's validation styles.
- Client-side validation is handled using the `checkValidity` method and Bootstrap's `was-validated` class.
- Server-side validation can be simulated by adding custom error messages dynamically.
- Ensure server-side validation logic is implemented on the server in production.
Recommended Links:
