In web development, forms are crucial components for collecting user information. Bootstrap 5 provides concise and efficient form styles and validation tools, allowing you to quickly build beautiful and fully functional forms without starting from scratch. This article will guide you through the core usage of Bootstrap 5 forms, from basic input fields and dropdown menus to form validation.
Why Use Bootstrap for Forms?¶
Bootstrap 5 form components use predefined CSS classes to quickly beautify form elements while supporting responsive layouts (adapting to mobile, tablet, and desktop devices). Compared to writing forms with pure HTML/CSS, Bootstrap significantly reduces styling code, enabling you to focus on functionality—especially ideal for beginners to get started quickly.
1. Basic Input Fields: Making Forms Neater¶
Input fields are the most basic element of a form. Bootstrap transforms input fields into modern, styled components with simple class names.
1.1 Basic Input Field Structure¶
A standard Bootstrap input field requires a label and an input, with class names optimizing styling and spacing:
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" placeholder="Please enter your username">
</div>
form-label: Styles the label for better readability.form-control: Core class for input fields, providing borders, rounded corners, padding, etc., for a polished look.mb-3: Short formargin-bottom, controls spacing between elements (3indicates spacing size; larger numbers mean more spacing).idandfor: Must match to associate the label with the input, allowing clicks on the label to focus the input.placeholder: Hint text inside the input to guide users.
1.2 Different Types of Input Fields¶
By modifying the type attribute, you can create various input fields. Bootstrap’s form-control class is universally supported:
- Text:
type="text"(default for general text) - Password:
type="password"(hides input content) - Email:
type="email"(automatically validates email format, with error prompts on submission) - Number:
type="number"(restricts input to numbers, supportingmin/maxattributes) - Date:
type="date"(pops up a date picker)
Example:
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control" id="email" placeholder="your@email.com">
</div>
<div class="mb-3">
<label for="age" class="form-label">Age</label>
<input type="number" class="form-control" id="age" min="1" max="120" placeholder="Please enter your age">
</div>
2. Dropdown Menus: Enriching Form Options¶
Dropdown menus are ideal for scenarios where users select from predefined options (e.g., gender, occupation, region). Bootstrap 5 simplifies dropdown styling with the form-select class.
2.1 Basic Dropdown Menu¶
Add the form-select class to the <select> tag for a Bootstrap-style dropdown:
<div class="mb-3">
<label for="gender" class="form-label">Gender</label>
<select class="form-select" id="gender">
<option>Please select</option>
<option>Male</option>
<option>Female</option>
<option>Prefer not to say</option>
</select>
</div>
form-select: Styles the dropdown (replaces the native ugly dropdown).option: Dropdown options; the firstoptionis typically a default prompt (e.g., “Please select”).
2.2 Multi-Select Dropdown (Requires JavaScript)¶
For multi-selection (e.g., selecting hobbies), use Bootstrap dropdown buttons with JavaScript:
<div class="mb-3">
<label class="form-label">Hobbies</label>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="hobbies" data-bs-toggle="dropdown">
Select hobbies
</button>
<ul class="dropdown-menu" aria-labelledby="hobbies">
<li><input class="form-check-input me-2" type="checkbox" id="reading"> <label class="form-check-label" for="reading">Reading</label></li>
<li><input class="form-check-input me-2" type="checkbox" id="sports"> <label class="form-check-label" for="sports">Sports</label></li>
<li><input class="form-check-input me-2" type="checkbox" id="music"> <label class="form-check-label" for="music">Music</label></li>
</ul>
</div>
</div>
dropdownseries classes: Control dropdown expansion/collapse; requires Bootstrap 5 JS (see “Including Bootstrap” below).
3. Form Validation: Ensuring Data Accuracy¶
Validating user input (e.g., required fields, format errors) before form submission is critical. Bootstrap 5 supports HTML5 native validation and custom feedback styles, enabling basic validation with minimal code.
3.1 Basic Validation: Required Fields & Format Checks¶
Use HTML5 required for mandatory fields and type attributes (e.g., email) for automatic format checks:
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" placeholder="Please enter your username" required>
<div class="invalid-feedback">Username cannot be empty</div>
</div>
<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 format</div>
</div>
required: Marks the field as mandatory; prevents form submission if empty.invalid-feedback: Error message displayed when validation fails (triggered byis-invalidclass, see below).
3.2 Manually Triggering Validation States¶
Control validation states manually using JavaScript or the is-valid/is-invalid classes:
<div class="mb-3">
<label for="phone" class="form-label">Phone Number</label>
<input type="tel" class="form-control" id="phone" placeholder="11-digit phone number" required>
<div class="valid-feedback">Format correct</div>
<div class="invalid-feedback">Please enter a valid 11-digit phone number</div>
</div>
<script>
// Example: Validate phone number on blur
document.getElementById("phone").addEventListener("blur", function() {
const value = this.value.trim();
const isValid = /^1[3-9]\d{9}$/.test(value); // Simple phone regex
this.classList.toggle("is-valid", isValid);
this.classList.toggle("is-invalid", !isValid);
});
</script>
is-valid/is-invalid: Manually mark validation success/failure, triggering correspondingvalid-feedback/invalid-feedbackmessages.
4. Comprehensive Example: Complete Form Implementation¶
Here’s a complete registration form example with inputs, dropdowns, and validation:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Bootstrap 5 Form Example</title>
<!-- Include Bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-4">
<form class="row g-3">
<!-- Left Column (6 columns) -->
<div class="col-md-6">
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" placeholder="Please enter your username" required>
<div class="invalid-feedback">Username cannot be empty</div>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" placeholder="Please enter your password" required minlength="6">
<div class="invalid-feedback">Password must be at least 6 characters</div>
</div>
</div>
<!-- Right Column (6 columns) -->
<div class="col-md-6">
<div class="mb-3">
<label for="gender" class="form-label">Gender</label>
<select class="form-select" id="gender" required>
<option>Please select</option>
<option>Male</option>
<option>Female</option>
</select>
</div>
<div class="mb-3">
<label for="phone" class="form-label">Phone Number</label>
<input type="tel" class="form-control" id="phone" placeholder="11-digit phone number" required>
<div class="invalid-feedback">Please enter a valid 11-digit phone number</div>
</div>
</div>
<!-- Submit Button -->
<div class="col-12">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
<!-- Include Bootstrap 5 JS (for dropdowns and other interactions) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
5. Key Tips Summary¶
- Spacing Control: Use
mb-3(bottom margin),mt-2(top margin), etc., to adjust spacing and avoid clutter. - Responsive Layout: Use
row+col-*(e.g.,col-md-6) for multi-column layouts that adapt to different screens. - Validation State Toggling: Dynamically control
is-valid/is-invalidwith JavaScript to enhance interaction. - Style Reusability: Add
row g-3to form containers for consistent spacing, and useform-controlfor all inputs to maintain style consistency.
Including Bootstrap 5¶
To use Bootstrap 5, include CSS and JS (if interactive features are needed) in your HTML head:
<!-- Only CSS (for basic styling) -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Add JS for interactions (dropdowns, modals, etc.) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
With the above content, you’ve mastered the core usage of Bootstrap 5 forms—from basic input field styling to dropdown menu expansion and validation logic. Experiment with different input types and validation rules to quickly build professional-grade forms!