In Bootstrap 5, form validation is a built-in feature that allows you to validate user input and provide feedback to the user. It helps ensure that the data entered by the user meets the specified criteria. Here’s how you can use form validation in Bootstrap 5:
- Basic Form Validation:
<form class="needs-validation" novalidate>
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" required>
<div class="invalid-feedback">Please enter your name.</div>
</div>
<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 address.</div>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
In this example, the needs-validation
class is added to the <form>
element to enable form validation. Each input field that requires validation has the required
attribute. The error message is displayed using the invalid-feedback
class within a <div>
element.
- Customizing Validation Styles:
Bootstrap 5 applies styles to invalid fields and displays error messages by default. You can further customize the validation styles using additional classes:
is-valid
: Applied to a validated input field to indicate that it is valid.is-invalid
: Applied to an input field with validation errors to indicate that it is invalid.
- Custom Validation Styles and Feedback:
<form class="was-validated">
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control is-invalid" id="password" required>
<div class="invalid-feedback">Please enter a valid password.</div>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
In this example, the was-validated
class is applied to the <form>
element to indicate that it has been validated. The input field is marked as invalid using the is-invalid
class, and a custom error message is displayed using the invalid-feedback
class.
- Custom JavaScript Validation:
Bootstrap 5 also provides JavaScript API for form validation, allowing you to customize the validation behavior programmatically. You can use JavaScript to handle form submission and implement custom validation logic.
These examples demonstrate how to use form validation in Bootstrap 5. By adding the necessary classes and attributes, you can enable validation and provide feedback to the user. Remember to include the necessary Bootstrap 5 CSS file and, if needed, Bootstrap’s JavaScript file for form validation to work properly.