Form validation is a critical step in front-end development to ensure the legitimacy of user input data. Whether registering an account, filling out order information, or submitting a comment, reasonable form validation can reduce invalid data submissions and enhance the user experience. As a popular front-end framework, Bootstrap 5 provides powerful and easy-to-use form validation features, allowing us to implement basic form checks without writing extensive JavaScript code. This article will guide you through the core usage of Bootstrap 5 form validation with simple and understandable steps.
一、准备工作:引入 Bootstrap5¶
First, include the Bootstrap 5 CSS and JavaScript files in your HTML file (JavaScript support is required for real-time feedback and interaction in form validation). The simplest way is to use a CDN. Add the following code in the <head> and before </body>:
<!-- Include Bootstrap5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Include Bootstrap5 JS (includes Popper.js for dropdowns and other components) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
二、基础表单验证:HTML5 属性 + Bootstrap 类¶
The core of Bootstrap 5 form validation is combining HTML5 form attributes (such as required and type) with Bootstrap built-in classes (such as form-control and invalid-feedback). Here is a complete example of a registration form with fields like email, password, confirm password, and age:
<form id="registrationForm" class="needs-validation" novalidate>
<!-- Email -->
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control" id="email"
placeholder="your@email.com" required>
<div class="invalid-feedback">Please enter a valid email address</div>
</div>
<!-- Password -->
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password"
minlength="8" required>
<div class="invalid-feedback">Password must be at least 8 characters long</div>
</div>
<!-- Confirm Password -->
<div class="mb-3">
<label for="confirmPassword" class="form-label">Confirm Password</label>
<input type="password" class="form-control" id="confirmPassword" required>
<div class="invalid-feedback">Passwords do not match</div>
</div>
<!-- Age -->
<div class="mb-3">
<label for="age" class="form-label">Age</label>
<input type="number" class="form-control" id="age"
min="18" max="120" required>
<div class="invalid-feedback">Age must be between 18-120</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Key Attribute and Class Explanation:¶
needs-validation: Marks the form as “needs validation”, triggering validation when the submit button is clicked by default.novalidate: Disables the browser’s default HTML5 validation (to avoid conflicts with Bootstrap).required: The field is mandatory; validation fails if left unfilled.type="email"/type="password"/type="number":email: Automatically validates the format (e.g., includes@and a domain).number: Restricts the value range usingmin/max(e.g., age 18-120).password: No special format validation, only length restriction (requiresminlength).form-control: Bootstrap’s base style for input fields, ensuring a responsive and visually consistent look.invalid-feedback: Container for error messages, showing a red border and error text when validation fails.
三、Validation States and Feedback¶
Bootstrap automatically adds is-valid (success) or is-invalid (error) classes to input fields when validation succeeds or fails, along with invalid-feedback to display hints.
- Success State: When input meets the rules, the input field shows a green border, and error messages are hidden.
- Error State: When input fails validation, the field shows a red border, and the
invalid-feedbackcontent is displayed.
四、Real-Time Validation (Triggered on Input)¶
By default, validation only triggers when the submit button is clicked. For real-time validation (during input), use JavaScript to listen for input events:
<script>
document.addEventListener('DOMContentLoaded', function() {
const forms = document.querySelectorAll('.needs-validation');
forms.forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault(); // Prevent submission
event.stopPropagation(); // Stop event bubbling
}
form.classList.add('was-validated'); // Show all validation results
}, false);
// Real-time validation example: Confirm Password
const password = document.getElementById('password');
const confirmPassword = document.getElementById('confirmPassword');
confirmPassword.addEventListener('input', () => {
if (password.value !== confirmPassword.value) {
confirmPassword.classList.add('is-invalid');
confirmPassword.setCustomValidity('Passwords do not match');
} else {
confirmPassword.classList.remove('is-invalid');
confirmPassword.setCustomValidity(''); // Clear error message
}
});
});
});
</script>
Core Method Explanation:¶
form.checkValidity(): Checks if the form meets the rules, returningtrue(valid) orfalse(invalid).form.classList.add('was-validated'): Forcibly displays all validation results (even if the form is not submitted).setCustomValidity('Error Message'): Customizes error messages (reset to''to clear the state).
五、Common Issues and Solutions¶
- Validation Not Working: Check if
needs-validationornovalidateattributes are missing. - No Real-Time Validation: Ensure JavaScript correctly listens for input events (e.g.,
input). - Error Messages Not Displaying: Verify
invalid-feedbackcontent is not empty and the input field has theis-invalidclass. - Styling Issues: Confirm Bootstrap CSS and JS files are correctly included, or that custom styles are not overriding built-in styles.
六、Summary¶
Bootstrap 5 form validation combines HTML5 native attributes + built-in CSS classes + simple JavaScript to achieve basic validation without complex code. Key steps:
1. Include Bootstrap CSS/JS.
2. Mark the form with needs-validation and novalidate.
3. Define rules using required, type, minlength, etc.
4. Use invalid-feedback to display error messages.
5. Optionally enhance with JavaScript for real-time validation and custom logic.
By following these steps, you can quickly implement robust front-end form validation, improving user experience and data quality.