
Bs5 Form Validation in Bootstrap
Sure! Here's a clear guide on Bootstrap 5 (BS5) Form Validation — built-in styles and behaviors to help you validate user inputs with visual feedback.
? How BS5 Form Validation Works
Bootstrap 5 uses HTML5 form validation APIs enhanced with its own CSS classes to show validation states like success or error. You just need to:
Use native HTML validation attributes (
required
,pattern
,type
, etc.)Add Bootstrap validation classes dynamically or via JavaScript
Style feedback messages with Bootstrap classes
? Basic Setup with HTML5 Validation
Add the novalidate
attribute to the <form>
tag to prevent default browser tooltips, then use Bootstrap's classes and feedback:
<form class="needs-validation" novalidate> <div class="mb-3"> <label for="validationCustom01" class="form-label">First name</label> <input type="text" class="form-control" id="validationCustom01" value="" required> <div class="valid-feedback"> Looks good! </div> <div class="invalid-feedback"> Please provide a first name. </div> </div> <button class="btn btn-primary" type="submit">Submit form</button></form>
needs-validation
: used to identify forms that need validation.valid-feedback
and.invalid-feedback
: messages shown on validation states
? JavaScript to Trigger Validation Styles
You need JavaScript to toggle .was-validated
on the form after submit:
(() => { 'use strict' const forms = document.querySelectorAll('.needs-validation') Array.from(forms).forEach(form => { form.addEventListener('submit', event => { if (!form.checkValidity()) { event.preventDefault() event.stopPropagation() } form.classList.add('was-validated') }, false) })})()
form.checkValidity()
uses the browser's native validationAdding
.was-validated
triggers Bootstrap styles
? Validation States
Class | Description |
---|---|
.is-valid | Applied to inputs when valid |
.is-invalid | Applied to inputs when invalid |
.valid-feedback | Message shown when input valid |
.invalid-feedback | Message shown when input invalid |
? Example with Custom Validation
<form class="needs-validation" novalidate> <input type="email" class="form-control" id="email" required> <div class="invalid-feedback"> Please enter a valid email address. </div> <button type="submit" class="btn btn-primary mt-3">Submit</button></form>
Use the same JS snippet above to enable validation feedback.
? Browser Support and Limitations
Uses built-in HTML5 validation — so support depends on browsers.
You can add your own custom validations via JavaScript if needed.
Would you like a full example with multiple inputs, or details on custom validation methods?