Bootstrap: 表单与表单验证

最后更新:2026-08-26

1. 本课导读

(1) 前置知识

(2) 🎯 你将学到


(3) 痛点

Bob 正在开发用户注册页面,需要收集姓名、邮箱、密码、国家选择和同意条款——Bootstrap 的表单 class 让他无需手写任何 CSS 样式,只需专注 HTML 结构和验证逻辑。

(4) 解法

表单是与用户交互的核心方式。Bootstrap 提供了统一的表单控件样式和验证反馈体系,让表单开发变得高效且美观。

理解方式: Bootstrap 表单 = 浏览器原生控件的美颜滤镜——所有 <input><select><textarea> 套上 .form-control 后,立刻获得统一样式、间距和交互反馈。

(5) 收益

借助 Bootstrap 的表单工具类,可以专注 HTML 结构和验证逻辑,无需编写任何 CSS 样式代码。


2. 表单控件

所有文本类输入控件使用 .form-control

▶ 示例:基础表单

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Form Demo</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  <div class="container py-4">
    <form>
      <div class="mb-3">
        <label for="name" class="form-label">Full Name</label>
        <input type="text" class="form-control" id="name" placeholder="Enter your name">
      </div>

      <div class="mb-3">
        <label for="country" class="form-label">Country</label>
        <select class="form-select" id="country">
          <option selected>Choose...</option>
          <option value="us">United States</option>
          <option value="jp">Japan</option>
          <option value="uk">United Kingdom</option>
        </select>
      </div>

      <div class="mb-3">
        <label class="form-label">Skills</label>
        <div class="form-check">
          <input class="form-check-input" type="checkbox" id="html" checked>
          <label class="form-check-label" for="html">HTML</label>
        </div>
        <div class="form-check">
          <input class="form-check-input" type="checkbox" id="css">
          <label class="form-check-label" for="css">CSS</label>
        </div>
      </div>

      <div class="mb-3">
        <label class="form-label">Experience Level</label>
        <div class="form-check">
          <input class="form-check-input" type="radio" name="level" id="beginner" checked>
          <label class="form-check-label" for="beginner">Beginner</label>
        </div>
        <div class="form-check">
          <input class="form-check-input" type="radio" name="level" id="advanced">
          <label class="form-check-label" for="advanced">Advanced</label>
        </div>
      </div>

      <button type="submit" class="btn btn-primary">Submit</button>
    </form>
  </div>
</body>
</html>
▶ 试一试

输出: Bootstrap 5.3 样式生效的组件效果(如按钮、卡片、轮播、折叠等),页面默认采用 Bootstrap 默认主题(亮色)和响应式网格。



3. 表单控件类型

控件 class 说明
Text input form-control 单行文本、email、password、url 等
Textarea form-control 多行文本(rows 控制行数)
Select form-select 下拉选择框
Checkbox form-check-input 多选
Radio form-check-input 单选(同 name 互斥)
Range form-range 滑块
File form-control 文件上传


4. 表单排版

(1) 网格布局

HTML
<div class="row">
  <div class="col-md-6 mb-3">
    <label for="firstName" class="form-label">First Name</label>
    <input type="text" class="form-control" id="firstName">
  </div>
  <div class="col-md-6 mb-3">
    <label for="lastName" class="form-label">Last Name</label>
    <input type="text" class="form-control" id="lastName">
  </div>
</div>
▶ 试一试

输出: Bootstrap 5.3 样式生效的组件效果(如按钮、卡片、轮播、折叠等),页面默认采用 Bootstrap 默认主题(亮色)和响应式网格。

(2) 行内表单

HTML
<form class="row g-3">
  <div class="col-auto">
    <input type="search" class="form-control" placeholder="Search...">
  </div>
  <div class="col-auto">
    <button class="btn btn-primary" type="submit">Go</button>
  </div>
</form>
▶ 试一试

输出: Bootstrap 5.3 样式生效的组件效果(如按钮、卡片、轮播、折叠等),页面默认采用 Bootstrap 默认主题(亮色)和响应式网格。

(3) 水平表单

HTML
<div class="row mb-3">
  <label for="email2" class="col-sm-2 col-form-label">Email</label>
  <div class="col-sm-10">
    <input type="email" class="form-control" id="email2">
  </div>
</div>
▶ 试一试

输出: Bootstrap 5.3 样式生效的组件效果(如按钮、卡片、轮播、折叠等),页面默认采用 Bootstrap 默认主题(亮色)和响应式网格。



5. 输入组

HTML
<div class="input-group mb-3">
  <span class="input-group-text">@</span>
  <input type="text" class="form-control" placeholder="Username">
</div>

<div class="input-group mb-3">
  <input type="text" class="form-control" placeholder="Amount">
  <span class="input-group-text">.00</span>
</div>

<div class="input-group mb-3">
  <button class="btn btn-outline-secondary" type="button">Search</button>
  <input type="text" class="form-control" placeholder="Type to search">
</div>
▶ 试一试

输出: Bootstrap 5.3 样式生效的组件效果(如按钮、卡片、轮播、折叠等),页面默认采用 Bootstrap 默认主题(亮色)和响应式网格。



6. 表单验证

HTML
<form class="row g-3 needs-validation" novalidate>
  <div class="col-md-4">
    <label for="validationName" class="form-label">First Name</label>
    <input type="text" class="form-control" id="validationName" required>
    <div class="valid-feedback">Looks good!</div>
    <div class="invalid-feedback">Please enter your name.</div>
  </div>

  <div class="col-md-4">
    <label for="validationEmail" class="form-label">Email</label>
    <input type="email" class="form-control" id="validationEmail" required>
    <div class="valid-feedback">Valid email!</div>
    <div class="invalid-feedback">Please provide a valid email.</div>
  </div>

  <div class="col-12">
    <button class="btn btn-primary" type="submit">Submit</button>
  </div>
</form>

<script>
  (function() {
    var forms = document.querySelectorAll('.needs-validation')
    Array.prototype.slice.call(forms).forEach(function(form) {
      form.addEventListener('submit', function(event) {
        if (!form.checkValidity()) {
          event.preventDefault()
          event.stopPropagation()
        }
        form.classList.add('was-validated')
      }, false)
    })
  })()
</script>
▶ 试一试

输出: Bootstrap 5.3 样式生效的组件效果(如按钮、卡片、轮播、折叠等),页面默认采用 Bootstrap 默认主题(亮色)和响应式网格。

(1) 验证反馈样式

class 条件 显示方式
.valid-feedback 输入合法 绿色文字
.invalid-feedback 输入非法 红色文字
.was-validated 表单提交后 触发所有反馈
is-valid / is-invalid 手动控制 状态边框


7. 更多表单示例

▶ 示例:完整注册表单(带验证)

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Signup Form</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  <div class="container py-4">
    <div class="card mx-auto" style="max-width: 500px;">
      <div class="card-header bg-primary text-white">
        <h4 class="mb-0">Create Account</h4>
      </div>
      <div class="card-body">
        <form class="needs-validation" novalidate>
          <div class="mb-3">
            <label for="fullName" class="form-label">Full Name</label>
            <input type="text" class="form-control" id="fullName" required>
            <div class="invalid-feedback">Please enter your name.</div>
          </div>
          <div class="mb-3">
            <label for="signupEmail" class="form-label">Email</label>
            <input type="email" class="form-control" id="signupEmail" required>
            <div class="invalid-feedback">Please enter a valid email.</div>
          </div>
          <div class="row mb-3">
            <div class="col-md-6">
              <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.</div>
            </div>
            <div class="col-md-6">
              <label for="confirmPwd" class="form-label">Confirm</label>
              <input type="password" class="form-control" id="confirmPwd" required>
              <div class="invalid-feedback">Passwords must match.</div>
            </div>
          </div>
          <div class="mb-3">
            <label for="countrySelect" class="form-label">Country</label>
            <select class="form-select" id="countrySelect" required>
              <option value="">Choose...</option>
              <option value="us">United States</option>
              <option value="uk">United Kingdom</option>
              <option value="jp">Japan</option>
            </select>
            <div class="invalid-feedback">Please select a country.</div>
          </div>
          <div class="mb-3 form-check">
            <input type="checkbox" class="form-check-input" id="agreeTerms" required>
            <label class="form-check-label" for="agreeTerms">I agree to the terms and conditions</label>
            <div class="invalid-feedback">You must agree to continue.</div>
          </div>
          <button type="submit" class="btn btn-primary w-100">Register</button>
        </form>
      </div>
    </div>
  </div>
  <script>
    (function() {
      var forms = document.querySelectorAll('.needs-validation')
      Array.prototype.slice.call(forms).forEach(function(form) {
        form.addEventListener('submit', function(event) {
          if (!form.checkValidity()) {
            event.preventDefault()
            event.stopPropagation()
          }
          form.classList.add('was-validated')
        }, false)
      })
    })()
  </script>
</body>
</html>
▶ 试一试

输出: Bootstrap 5.3 样式生效的组件效果(如按钮、卡片、轮播、折叠等),页面默认采用 Bootstrap 默认主题(亮色)和响应式网格。

▶ 示例:搜索表单(输入组)

HTML
<form class="container py-4">
  <div class="row g-2">
    <div class="col-md-3">
      <select class="form-select">
        <option selected>All Categories</option>
        <option value="electronics">Electronics</option>
        <option value="clothing">Clothing</option>
        <option value="books">Books</option>
      </select>
    </div>
    <div class="col-md-6">
      <div class="input-group">
        <input type="search" class="form-control" placeholder="Search products...">
        <button class="btn btn-primary" type="submit">Search</button>
      </div>
    </div>
    <div class="col-md-3">
      <button class="btn btn-outline-secondary w-100" type="button">Advanced Filters</button>
    </div>
  </div>
</form>
▶ 试一试

输出: Bootstrap 5.3 样式生效的组件效果(如按钮、卡片、轮播、折叠等),页面默认采用 Bootstrap 默认主题(亮色)和响应式网格。

▶ 示例:行内表单

HTML
<form class="row row-cols-lg-auto g-3 align-items-center">
  <div class="col-12">
    <input type="text" class="form-control" placeholder="Username">
  </div>
  <div class="col-12">
    <input type="password" class="form-control" placeholder="Password">
  </div>
  <div class="col-12">
    <div class="form-check">
      <input class="form-check-input" type="checkbox" id="rememberMe">
      <label class="form-check-label" for="rememberMe">Remember me</label>
    </div>
  </div>
  <div class="col-12">
    <button type="submit" class="btn btn-primary">Sign In</button>
  </div>
</form>
▶ 试一试

输出: Bootstrap 5.3 样式生效的组件效果(如按钮、卡片、轮播、折叠等),页面默认采用 Bootstrap 默认主题(亮色)和响应式网格。

▶ 示例:浮动标签表单

HTML
<div class="container py-4" style="max-width: 400px;">
  <form>
    <div class="form-floating mb-3">
      <input type="email" class="form-control" id="floatingEmail" placeholder="name@example.com">
      <label for="floatingEmail">Email address</label>
    </div>
    <div class="form-floating mb-3">
      <input type="password" class="form-control" id="floatingPassword" placeholder="Password">
      <label for="floatingPassword">Password</label>
    </div>
    <div class="form-floating mb-3">
      <select class="form-select" id="floatingSelect">
        <option value="">Choose...</option>
        <option value="free">Free Plan</option>
        <option value="pro">Pro Plan</option>
        <option value="enterprise">Enterprise</option>
      </select>
      <label for="floatingSelect">Subscription Plan</label>
    </div>
    <div class="form-floating mb-3">
      <textarea class="form-control" id="floatingTextarea" style="height: 100px" placeholder="Comments"></textarea>
      <label for="floatingTextarea">Message</label>
    </div>
    <button class="btn btn-primary w-100">Submit</button>
  </form>
</div>
▶ 试一试

输出: Bootstrap 5.3 样式生效的组件效果(如按钮、卡片、轮播、折叠等),页面默认采用 Bootstrap 默认主题(亮色)和响应式网格。

(1) 表单布局决策流

100%
flowchart TD
    A[开始设计表单] --> B{字段数量}
    B -->|1-3 个| C[简单堆叠<br/>mb-3 分隔]
    B -->|4-8 个| D{是否需要分组}
    D -->|是| E[网格布局<br/>row + col-*]
    D -->|否| F[行内/水平布局]
    B -->|8+ 个| G[多列网格<br/>或分步骤]
    E --> H{是否需要前缀}
    H -->|是| I[input-group]
    H -->|否| J[直接 form-control]
    F --> K{浮动标签?}
    K -->|是| L[form-floating]
    K -->|否| M[普通 label]

输出: Bootstrap 5.3 样式生效的组件效果(如按钮、卡片、轮播、折叠等),页面默认采用 Bootstrap 默认主题(亮色)和响应式网格。

表单控件 class 适用数据类型
单行文本 form-control 姓名、邮箱、密码
多行文本 form-control (textarea) 评论、描述
下拉选择 form-select 国家、分类、选项
复选框 form-check-input 多选、同意条款
单选按钮 form-check-input (radio) 性别、等级、选项
滑块 form-range 价格范围、评分
文件上传 form-control (file) 图片、文档
输入组变体 代码模式 用例
前缀文字 input-group-text + form-control 金额 $、用户名 @ 前缀
后缀文字 form-control + input-group-text 后缀 .00、单位 px
前缀按钮 button + form-control 搜索框
后缀按钮 form-control + button 密码显示切换
多元素 多个 input-group-text 日期范围、组合输入
验证状态 class 边框 反馈文字
合法 is-valid 绿色 valid-feedback
非法 is-invalid 红色 invalid-feedback
提交后 was-validated 自动切换 触发所有反馈
工具提示 配合 valid-tooltip 同上 气泡式提示

❓ 常见问题

Q 表单控件为什么没有自带宽度?
A .form-control 默认 width: 100%。要控制宽度,放在网格列中(col-*)或加 style="width: 300px"
Q .form-label 有什么作用?
A 它统一了 <label> 的间距(margin-bottom: 0.5rem)和字号。不写也能工作,但推荐加上保持一致性。
Q 可以在表单验证中自定义错误信息吗?
A 可以。<div class="invalid-feedback"> 中的文字可以随意写。此外也支持 setCustomValidity() 方法。
Q 输入组可以嵌套多个元素吗?
A 可以。input-group 可以包含多个 input-group-textform-control 和按钮。
Q 浮动标签(form-floating)支持所有浏览器吗?
A 浮动标签使用了 CSS :placeholder-shown 伪类,现代浏览器均支持。IE 不支持,但 IE 已停止维护。如果需要兼容非常老的浏览器,建议使用传统标签布局。

📖 小节


📝 作业

  1. ⭐ 创建一个完整的注册表单:姓名(text)、年龄(number)、国家(select)、密码(password)、确认密码,全部用 Bootstrap 样式。
  2. ⭐⭐ 实现作业 1 的表单验证:姓名必填 2-20 字符、密码至少 8 位、邮箱格式正确,不符合时显示红色 invalid-feedback
  3. ⭐⭐⭐ 创建一个搜索输入组:左侧 form-select 选择分类 + 中间 form-control 搜索框 + 右侧按钮 Search。

上一课: 表格 · 下一课: 轮播图与模态框

Web-Tutorial.com

Web-Tutorial 技术团队

由多位开发者共同维护的编程教程平台。每篇教程由对应领域的开发者编写和审核,确保内容准确可靠。如发现任何问题,欢迎向我们反馈。

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏