Bootstrap 5 Forms and Validation: A Practical Walkthrough

Bootstrap 5 dropped jQuery and rebuilt forms around modern HTML. The result is markup that's both shorter and more accessible than v4.
The standard form layout
<form class="needs-validation" novalidate>
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input id="email" type="email" class="form-control" required>
<div class="invalid-feedback">Please enter a valid email.</div>
</div>
<button class="btn btn-primary" type="submit">Sign up</button>
</form>Floating labels
<div class="form-floating mb-3">
<input id="name" type="text" class="form-control" placeholder="Your name">
<label for="name">Your name</label>
</div>Floating labels need a placeholder attribute even if it's not visible โ Bootstrap uses it to keep the label position correct.
Wiring up validation
document.querySelectorAll('.needs-validation').forEach(form => {
form.addEventListener('submit', e => {
if (!form.checkValidity()) {
e.preventDefault(); e.stopPropagation();
}
form.classList.add('was-validated');
});
});Input groups
<div class="input-group">
<span class="input-group-text">@</span>
<input type="text" class="form-control" placeholder="username">
</div>Accessibility checklist
- Every input has a <label>
- Required fields use aria-required or the required attribute
- Feedback divs have meaningful text, not just colour
- Use type="email", type="tel", etc. for mobile keyboards
Frequently asked questions
Do Bootstrap forms need JavaScript?
Only for the validation feedback styling. The HTML5 validation works on its own.
Can I use floating labels with selects?
Yes โ wrap a <select class="form-select"> in .form-floating exactly like an input.
External references
Enjoyed this article?
Share it with a fellow developer or explore more tutorials in our blog.
More articles