How to create a form with validation in Bootstrap
使用Bootstrap 5创建带验证的表单需在form标签添加needs-validation和novalidate类,并引入Bootstrap CSS和JS;2. 表单字段通过required、type="email"、minlength等HTML5属性实现验证,并添加invalid-feedback显示错误信息;3. 通过JavaScript监听submit事件,调用checkValidity()方法并阻止无效表单提交,同时添加was-validated类触发展示错误提示;4. 可自定义CSS为有效输入添加成功样式,如绿色边框和对勾图标;5. 最终实现一个响应式、客户端验证、用户体验良好的表单,且无需额外库支持,完全基于Bootstrap原生功能完成。

Creating a form with validation in Bootstrap is straightforward, especially when using Bootstrap 5’s built-in validation styles and JavaScript. Here’s how to build a clean, responsive form with client-side validation using Bootstrap’s native features.

Set up the HTML structure with Bootstrap
Start by including Bootstrap 5 in your project. You can use the CDN for simplicity:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bootstrap Form with Validation</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container mt-5">
<form class="row g-3 needs-validation" novalidate>
<!-- Form fields go here -->
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>Key points:

- Use
needs-validationon the<form>to enable validation styles. - Add
novalidateto disable the browser’s default tooltip and allow Bootstrap’s custom styles. - Include the Bootstrap JS bundle for form validation support.
Add form fields with validation rules
Inside the form, create input fields and apply validation using HTML5 attributes like required, pattern, etc. Bootstrap will style them based on :valid and :invalid states.
Example with name, email, and password:

<!-- Name field -->
<div class="col-md-12">
<label for="fullName" class="form-label">Full Name</label>
<input type="text" class="form-control" id="fullName" placeholder="John Doe" required>
<div class="invalid-feedback">
Please enter your full name.
</div>
</div>
<!-- Email field -->
<div class="col-md-12">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control" id="email" placeholder="name@example.com" required>
<div class="invalid-feedback">
Please enter a valid email address.
</div>
</div>
<!-- Password field -->
<div class="col-md-12">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" required minlength="8">
<div class="invalid-feedback">
Password must be at least 8 characters long.
</div>
</div>
<!-- Submit button -->
<div class="col-12">
<button class="btn btn-primary" type="submit">Submit</button>
</div>Each field has:
requiredto make it mandatory.minlengthortype="email"for basic format checks.- A sibling
div.invalid-feedbackthat shows the error message when validation fails.
Enable JavaScript validation
Bootstrap requires a small script to trigger validation when the form is submitted.
Add this at the bottom of your <body> (after the form):
<script>
(() => {
'use strict';
// Fetch all forms we want to apply custom Bootstrap validation styles to
const forms = document.querySelectorAll('.needs-validation');
// Loop over them and prevent submission if invalid
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
})();
</script>What this does:
- Listens for the
submitevent. - Checks if the form is valid using
checkValidity(). - Prevents submission if invalid.
- Adds the
was-validatedclass to show error messages via Bootstrap’s.invalid-feedback.
Customize validation feedback (optional)
You can style feedback further or add success indicators. For example, to show a check mark on valid fields:
.was-validated .form-control:valid {
border-color: #198754;
padding-right: calc(1.5em + 0.75rem);
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23198754' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
background-repeat: no-repeat;
background-position: right calc(0.375em + 0.1875rem) center;
background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}This mimics Bootstrap’s default success styling if not already enabled.
Basically, Bootstrap handles most of the visual work. You just need to:
- Use the right classes and attributes.
- Add the validation script.
- Provide clear feedback messages.
It’s not flashy, but it’s effective and mobile-ready out of the box.
The above is the detailed content of How to create a form with validation in Bootstrap. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20519
7
13632
4
How to animate Bootstrap components for a more dynamic feel? (Advanced CSS)
Mar 13, 2026 am 01:13 AM
The fade and show classes of Bootstrap5 are only status markers and do not contain animation logic. You need to manually add @keyframes or transitions to achieve fade-in and fade-out; custom components need to configure additional animation rules, and when JS controls the display, the show class must be added with delay to ensure redrawing.
How to ensure your Bootstrap site is fully accessible (WCAG)? (Accessibility)
Mar 08, 2026 am 01:25 AM
The Bootstrap component does not automatically add the aria attributes required for complete WCAG. You need to manually complete aria-expanded, role="dialog", aria-labelledby, etc.; the form must be equipped with an explicit label; :focus needs to use :focus-visible to ensure that the keyboard focus is visible; the color contrast must reach 4.5:1.
How to create a professional-looking landing page with Bootstrap? (Project-Based)
Mar 10, 2026 am 12:22 AM
Bootstrap’sdefaultstylingfeelsgenericduetouncustomizedspacing,typography,andcolor—fixableviaCSSvariablesorSass,notdirectedits;avoidfixedwidths,misuseofgridclasses,andrender-blockingassetstoensureresponsivenessandfastLCP.
How to integrate Bootstrap with a JavaScript framework like React or Vue? (Integration)
Mar 12, 2026 am 01:22 AM
Only BootstrapCSS should be introduced in React/Vue instead of JS to avoid global style pollution and jQuery dependency; SCSS modules should be imported on demand to reduce the size; interactive functions must be imported with encapsulation libraries (such as react-bootstrap) or ESM; grid classes need to adapt to JSX/Vue syntax, and explicit and implicit classes should be used with SSR with caution.
How to implement a carousel or image slider with Bootstrap? (Content Display)
Mar 07, 2026 am 01:01 AM
Need not. Bootstrap5's carousel is automatically initialized by default. You need to manually call newbootstrap.Carousel() only when data-bs-ride is modified or the element is dynamically inserted.
How to properly install and set up Bootstrap 5 in your web project? (Getting Started)
Mar 16, 2026 am 12:40 AM
To correctly introduce Bootstrap5, you need to load bootstrap.min.css first, then load bootstrap.bundle.min.js (including Popper), and ensure that the viewport tag exists; after npm installation, you need to manually introduce compiled files in the dist directory. SCSS customization must be preceded by variable declarations, and JS components must be explicitly initialized to avoid jQuery contamination.
How to use Bootstrap utility classes to speed up your workflow? (Efficiency)
Mar 11, 2026 am 12:18 AM
Use mt-3 to represent the top margin, mb-3 to represent the bottom margin, and the suffixes t/b/s/e correspond to top/bottom/start/end respectively; ms-auto implements right alignment in the flex container, me-2 replaces the abandoned mr-2, and responsive classes such as mt-md-4 need to have breakpoint prefixes.
How to use Bootstrap variables to maintain a consistent color scheme? (Branding)
Mar 14, 2026 am 12:59 AM
The safest way is to redefine Bootstrap's Sass variables (such as $primary, $primary-rgb, $primary-text-emphasis) in advance and introduce them before @import "bootstrap/scss/variables" to ensure that all dependent variables are updated synchronously to avoid compilation failure or style exceptions.





