You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bootstrap 4 CSS中实现表单验证?

如何在Bootstrap 4中实现表单验证?

我来给你详细讲讲Bootstrap 4里表单验证的实现方式,它主要是通过添加特定的状态类来标记表单控件的验证状态,不用复杂的JS就能实现基础的视觉反馈~

核心实现思路

Bootstrap 4的表单验证依赖几个核心类,用来给表单组、控件添加对应的样式和反馈信息:

  • has-success/has-danger/has-warning:添加在.form-group容器上,标记整个表单组的验证状态
  • form-control-success/form-control-danger/form-control-warning:添加在<input>/<select>等表单控件上,给控件本身加上对应状态的样式
  • form-control-feedback:用来显示验证的反馈文本,会自动匹配对应状态的颜色

成功状态示例(对应你提到的文档示例)

<div class="form-group has-success">
  <label class="form-control-label" for="inputSuccess1">Input with success</label>
  <input type="text" class="form-control form-control-success" id="inputSuccess1">
  <div class="form-control-feedback">Success! You've done it.</div>
  <small class="form-text text-muted">Example help text that remains unchanged.</small>
</div>

这里的每个类作用:

  • .has-success 让整个表单组的标签、控件边框都变成Bootstrap默认的成功绿色
  • .form-control-success 给输入框加上成功状态的边框样式
  • .form-control-feedback 显示成功提示文本,颜色会自动匹配成功状态

错误/警告状态示例

同理,替换对应的类就能实现错误或警告状态的验证样式:

错误状态

<div class="form-group has-danger">
  <label class="form-control-label" for="inputDanger1">Input with danger</label>
  <input type="text" class="form-control form-control-danger" id="inputDanger1">
  <div class="form-control-feedback">Oops, that's not right.</div>
  <small class="form-text text-muted">Example help text that remains unchanged.</small>
</div>

警告状态

<div class="form-group has-warning">
  <label class="form-control-label" for="inputWarning1">Input with warning</label>
  <input type="text" class="form-control form-control-warning" id="inputWarning1">
  <div class="form-control-feedback">Hmm, you might want to check this.</div>
  <small class="form-text text-muted">Example help text that remains unchanged.</small>
</div>

结合JavaScript实现动态验证

如果需要根据用户输入动态切换验证状态,你可以用JS来添加/移除这些类。举个简单的实时验证例子:

// 监听输入框的输入事件
document.getElementById('inputSuccess1').addEventListener('input', function(e) {
  const formGroup = this.closest('.form-group');
  const feedbackText = formGroup.querySelector('.form-control-feedback');
  
  if (this.value.length >= 3) {
    // 切换为成功状态
    formGroup.classList.add('has-success');
    formGroup.classList.remove('has-danger');
    this.classList.add('form-control-success');
    this.classList.remove('form-control-danger');
    feedbackText.textContent = 'Success! You\'ve done it.';
  } else {
    // 切换为错误状态
    formGroup.classList.add('has-danger');
    formGroup.classList.remove('has-success');
    this.classList.add('form-control-danger');
    this.classList.remove('form-control-success');
    feedbackText.textContent = 'Please enter at least 3 characters.';
  }
});

内容的提问来源于stack exchange,提问作者Janka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:19:22