表单(Forms)

Bootstrap提供了一些表单控件样式、布局选项,以及用来创建广泛多样化的的表单的自定义组件,以下是示例和使用指南。

概览

Bootstrap的表单控件使用了 CSS样式重置,使用这些Class类来自定义显示,以便跨越浏览器和设备获得一致的呈现。

确保在输入框上使用正确的 type 属性(如email 用于电子邮件地址或 number 用于数字录入) 从而利用较新的录入控制,包括诸如电子邮件验证、号码选择等。

以下是演示Bootstrap表单样式的一个经典示例展示,并推荐继续向下阅读有关class类、表单布局等文档。

We'll never share your email with anyone else.
<form>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
    <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
  </div>
  <div class="form-check">
    <input type="checkbox" class="form-check-input" id="exampleCheck1">
    <label class="form-check-label" for="exampleCheck1">Check me out</label>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

表单控件

文本控件(如 <input><select><textarea>)统一采用 .form-control 样式进行处理优化,包括常规外观、focus选(点)中状态、尺寸大小等。

推荐浏览 自定义表单 以进一步了解 <select>控件的风格设计。

<form>
  <div class="form-group">
    <label for="exampleFormControlInput1">Email address</label>
    <input type="email" class="form-control" id="exampleFormControlInput1" placeholder="name@example.com">
  </div>
  <div class="form-group">
    <label for="exampleFormControlSelect1">Example select</label>
    <select class="form-control" id="exampleFormControlSelect1">
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
    </select>
  </div>
  <div class="form-group">
    <label for="exampleFormControlSelect2">Example multiple select</label>
    <select multiple class="form-control" id="exampleFormControlSelect2">
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
    </select>
  </div>
  <div class="form-group">
    <label for="exampleFormControlTextarea1">Example textarea</label>
    <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
  </div>
</form>

对于input文件选择控件,Bootstrap v4采用.form-control-file 取代了.form-control

<form>
  <div class="form-group">
    <label for="exampleFormControlFile1">Example file input</label>
    <input type="file" class="form-control-file" id="exampleFormControlFile1">
  </div>
</form>

大小规格

使用 .form-control-lg.form-control-sm属性定控件大小高度。

<input class="form-control form-control-lg" type="text" placeholder=".form-control-lg">
<input class="form-control" type="text" placeholder="Default input">
<input class="form-control form-control-sm" type="text" placeholder=".form-control-sm">
<select class="form-control form-control-lg">
  <option>Large select</option>
</select>
<select class="form-control">
  <option>Default select</option>
</select>
<select class="form-control form-control-sm">
  <option>Small select</option>
</select>

输入范围

使用设置水平滚动范围输入.form-control-range

<form>
  <div class="form-group">
    <label for="formControlRange">Example Range input</label>
    <input type="range" class="form-control-range" id="formControlRange">
  </div>
</form>

只读属性

在input控件上增加 readonly (布尔值)标签定义,以防止修改input中的值。仅能阅读的input控件显示较谈(就象禁用的输入框),但保留鼠标效果。

<input class="form-control" type="text" placeholder="Readonly input here…" readonly>

只读纯文本

如果你希望将 <input readonly>属性进一步处理,显示为纯文本(没有控件框),你只要引用 .form-control-plaintext class样式,就能移除预设的表单样式,并保留适当的边距和填充间隙。

<form>
  <div class="form-group row">
    <label for="staticEmail" class="col-sm-2 col-form-label">Email</label>
    <div class="col-sm-10">
      <input type="text" readonly class="form-control-plaintext" id="staticEmail" value="email@example.com">
    </div>
  </div>
  <div class="form-group row">
    <label for="inputPassword" class="col-sm-2 col-form-label">Password</label>
    <div class="col-sm-10">
      <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    </div>
  </div>
</form>
<form class="form-inline mb-2">
  <div class="form-group">
    <label for="staticEmail2" class="sr-only">Email</label>
    <input type="text" readonly class="form-control-plaintext" id="staticEmail2" value="email@example.com">
  </div>
  <div class="form-group mx-sm-3 mb-2">
    <label for="inputPassword2" class="sr-only">Password</label>
    <input type="password" class="form-control" id="inputPassword2" placeholder="Password">
  </div>
  <button type="submit" class="btn btn-primary mb-2">Confirm identity</button>
</form>

复选框与单选框

使用.form-check 可以格式化复选框和单选框按钮,用以改进它们的默认布局和动作呈现,复选框用于在列表中选择一个或多个选项,单选框则用于多许多选项中选择一个。

复选框和单选框也是可以禁用的,只要not-allowed在父级的悬停上提供定义,<label>需要将该.disabled 类添加到父级.form-check,同时控件也会淡化文字颜色以灰色显示禁用状态。

默认堆叠

默认情况下,同级任意数量的复选框与单选框按钮垂直堆叠,并与.form-check有间隙隔离。

<div class="form-check">
  <input class="form-check-input" type="checkbox" value="" id="defaultCheck1">
  <label class="form-check-label" for="defaultCheck1">
    Option one is this and that—be sure to include why it's great
  </label>
</div>
<div class="form-check">
  <input class="form-check-input" type="checkbox" value="" id="defaultCheck2" disabled>
  <label class="form-check-label" for="defaultCheck2">
     Option two is disabled
  </label>
</div>
<div class="form-check">
  <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios1" value="option1" checked>
  <label class="form-check-label" for="exampleRadios1">
   Option one is this and that—be sure to include why it's great 
  </label>
</div>
<div class="form-check">
  <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios2" value="option2">
  <label class="form-check-label" for="exampleRadios2">
    Option two can be something else and selecting it will deselect option one
  </label>
</div>
<div class="form-check disabled">
  <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios3" value="option3" disabled>
  <label class="form-check-label" for="exampleRadios3">
    Option three is disabled 
  </label>
</div>

水平排列

通过添加 .form-check-inline到任何一个组,会使 加到任何.form-check中的选取框平行排列。

<div class="form-check form-check-inline">
  <input class="form-check-input" type="checkbox" id="inlineCheckbox1" value="option1">
  <label class="form-check-label" for="inlineCheckbox1">1</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="checkbox" id="inlineCheckbox2" value="option2">
  <label class="form-check-label" for="inlineCheckbox2">2</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="checkbox" id="inlineCheckbox3" value="option3" disabled>
  <label class="form-check-label" for="inlineCheckbox3">3 (disabled)</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="option1">
  <label class="form-check-label" for="inlineRadio1">1</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="option2">
  <label class="form-check-label" for="inlineRadio2">2</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio3" value="option3" disabled>
  <label class="form-check-label" for="inlineRadio3">3 (disabled)</label>
</div>

没有标签

添加 .position-static.form-check 选择器上,可以实现没有文本的输入,记住:仍然要为辅助浏览(友好访问)提供相应标签,如使用 aria-label定义。

<div class="form-check">
  <input class="form-check-input position-static" type="checkbox" id="blankCheckbox" value="option1" aria-label="...">
</div>
<div class="form-check">
  <input class="form-check-input position-static" type="radio" name="blankRadio" id="blankRadio1" value="option1" aria-label="...">
</div>

布局

自从 Bootstrap 使用display: blockwidth: 100% 在全部的 input 控件上后,表单默认都是基于垂直堆叠排列的,可以使用其它Class类来改变表单的布局。

表单组

.form-group 群组可以向为表单赋予一些结构样式,其唯一目的是提供标签的控制配对以及margin-bottom 属性,由于它是一个class选择器,你可以在<fieldset><div>或任何其它元素中使用它。

<form>
  <div class="form-group">
    <label for="formGroupExampleInput">Example label</label>
    <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
  </div>
  <div class="form-group">
    <label for="formGroupExampleInput2">Another label</label>
    <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
  </div>
</form>

表单栅格排列

可使用我们的栅格系统构建更复杂的表单,包括建立多列、多种宽度和其它对齐选项的布局。

<form>
  <div class="row">
    <div class="col">
      <input type="text" class="form-control" placeholder="First name">
    </div>
    <div class="col">
      <input type="text" class="form-control" placeholder="Last name">
    </div>
  </div>
</form>

表格式排列

你也可以使用 .form-row来取代.row(它们二者很多时候可以互换使用),因为.form-row提供更小的沟槽缝隙。

<form>
  <div class="form-row">
    <div class="col">
      <input type="text" class="form-control" placeholder="First name">
    </div>
    <div class="col">
      <input type="text" class="form-control" placeholder="Last name">
    </div>
  </div>
</form>

还可以使用栅格系统建立更复杂的布局。

<form>
  <div class="form-row">
    <div class="form-group col-md-6">
      <label for="inputEmail4">Email</label>
      <input type="email" class="form-control" id="inputEmail4" placeholder="Email">
    </div>
    <div class="form-group col-md-6">
      <label for="inputPassword4">Password</label>
      <input type="password" class="form-control" id="inputPassword4" placeholder="Password">
    </div>
  </div>
  <div class="form-group">
    <label for="inputAddress">Address</label>
    <input type="text" class="form-control" id="inputAddress" placeholder="1234 Main St">
  </div>
  <div class="form-group">
    <label for="inputAddress2">Address 2</label>
    <input type="text" class="form-control" id="inputAddress2" placeholder="Apartment, studio, or floor">
  </div>
  <div class="form-row">
    <div class="form-group col-md-6">
      <label for="inputCity">City</label>
      <input type="text" class="form-control" id="inputCity">
    </div>
    <div class="form-group col-md-4">
      <label for="inputState">State</label>
      <select id="inputState" class="form-control">
        <option selected>Choose...</option>
        <option>...</option>
      </select>
    </div>
    <div class="form-group col-md-2">
      <label for="inputZip">Zip</label>
      <input type="text" class="form-control" id="inputZip">
    </div>
  </div>
  <div class="form-group">
    <div class="form-check">
      <input class="form-check-input" type="checkbox" id="gridCheck">
      <label class="form-check-label" for="gridCheck">
        Check me out
      </label>
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Sign in</button>
</form>

垂直排列表单

通过添加 .row class类,并使用 .col-*-* 等栅格组件来指定标签和宽度,可以建立起水平表单。

确保添加.col-form-label 到您<label>上,以便他们垂直居中与他们相关的表单控件。<legend>元素,可以.col-form-legend样式定义,与普通<label>元素相似。.

Radios
Checkbox
<form>
  <div class="form-group row">
    <label for="inputEmail3" class="col-sm-2 col-form-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" id="inputEmail3" placeholder="Email">
    </div>
  </div>
  <div class="form-group row">
    <label for="inputPassword3" class="col-sm-2 col-form-label">Password</label>
    <div class="col-sm-10">
      <input type="password" class="form-control" id="inputPassword3" placeholder="Password">
    </div>
  </div>
  <fieldset class="form-group">
    <div class="row">
      <legend class="col-form-label col-sm-2 pt-0">Radios</legend>
      <div class="col-sm-10">
        <div class="form-check">
          <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios1" value="option1" checked>
          <label class="form-check-label" for="gridRadios1">
            First radio
          </label>
        </div>
        <div class="form-check">
          <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios2" value="option2">
          <label class="form-check-label" for="gridRadios2">
            Second radio
          </label>
        </div>
        <div class="form-check disabled">
          <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios3" value="option3" disabled>
          <label class="form-check-label" for="gridRadios3">
            Third disabled radio
          </label>
        </div>
      </div>
    </div>
  </fieldset>
  <div class="form-group row">
    <div class="col-sm-2">Checkbox</div>
    <div class="col-sm-10">
      <div class="form-check">
        <input class="form-check-input" type="checkbox" id="gridCheck1">
        <label class="form-check-label" for="gridCheck1">
          Example checkbox
        </label>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <div class="col-sm-10">
      <button type="submit" class="btn btn-primary">Sign in</button>
    </div>
  </div>
</form>
垂直排列表单尺寸规格定义

使用.col-form-label-sm.col-form-label-lg<label>上,可以定义控件大小,还有 .form-control-lg.form-control-sm样式也起相应作用。

<form>
  <div class="form-group row">
    <label for="colFormLabelSm" class="col-sm-2 col-form-label col-form-label-sm">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control form-control-sm" id="colFormLabelSm" placeholder="col-form-label-sm">
    </div>
  </div>
  <div class="form-group row">
    <label for="colFormLabel" class="col-sm-2 col-form-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" id="colFormLabel" placeholder="col-form-label">
    </div>
  </div>
  <div class="form-group row">
    <label for="colFormLabelLg" class="col-sm-2 col-form-label col-form-label-lg">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control form-control-lg" id="colFormLabelLg" placeholder="col-form-label-lg">
    </div>
  </div>
</form>

栅格式列尺寸定义

如前面的示例所示,我們的栅格系統允許您将任意数量的的 code class="highlighter-rouge">.col放置在 code class="highlighter-rouge">.row 或 code class="highlighter-rouge">.form-row中,它们会在自动进行宽度分割(根据你的栅格定义),从而定义某列更窄或某列更宽(其余列享受流式布局宽度定义)。

<form>
  <div class="form-row">
    <div class="col-7">
      <input type="text" class="form-control" placeholder="City">
    </div>
    <div class="col">
      <input type="text" class="form-control" placeholder="State">
    </div>
    <div class="col">
      <input type="text" class="form-control" placeholder="Zip">
    </div>
  </div>
</form>

自动调整大小

下面的示例使用一个flexbox弹性布局垂直居中的内容,我们将.col改为.col-auto,这样的列只占用本身内容所需要的宽度,换句话说列的大小就是内容的大小(宽度)

@
<form>
  <div class="form-row align-items-center">
    <div class="col-auto">
      <label class="sr-only" for="inlineFormInput">Name</label>
      <input type="text" class="form-control mb-2" id="inlineFormInput" placeholder="Jane Doe">
    </div>
    <div class="col-auto">
      <label class="sr-only" for="inlineFormInputGroup">Username</label>
      <div class="input-group mb-2">
        <div class="input-group-prepend">
          <div class="input-group-text">@</div>
        </div>
        <input type="text" class="form-control" id="inlineFormInputGroup" placeholder="Username">
      </div>
    </div>
    <div class="col-auto">
      <div class="form-check mb-2">
        <input class="form-check-input" type="checkbox" id="autoSizingCheck">
        <label class="form-check-label" for="autoSizingCheck">
          Remember me
        </label>
      </div>
    </div>
    <div class="col-auto">
      <button type="submit" class="btn btn-primary mb-2">Submit</button>
    </div>
  </div>
</form>

然后,你可以重新混合不同大小的class样式。

@
<form>
  <div class="form-row align-items-center">
    <div class="col-sm-3 my-1">
      <label class="sr-only" for="inlineFormInputName">Name</label>
      <input type="text" class="form-control" id="inlineFormInputName" placeholder="Jane Doe">
    </div>
    <div class="col-sm-3 my-1">
      <label class="sr-only" for="inlineFormInputGroupUsername">Username</label>
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">@</div>
        </div>
        <input type="text" class="form-control" id="inlineFormInputGroupUsername" placeholder="Username">
      </div>
    </div>
    <div class="col-auto my-1">
      <div class="form-check">
        <input class="form-check-input" type="checkbox" id="autoSizingCheck2">
        <label class="form-check-label" for="autoSizingCheck2">
          Remember me
        </label>
      </div>
    </div>
    <div class="col-auto my-1">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
  </div>
</form>

也支持 自定义表单 控件。.

<form>
  <div class="form-row align-items-center">
    <div class="col-auto my-1">
      <label class="mr-sm-2" for="inlineFormCustomSelect">Preference</label>
      <select class="custom-select mr-sm-2" id="inlineFormCustomSelect">
        <option selected>Choose...</option>
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
      </select>
    </div>
    <div class="col-auto my-1">
      <div class="custom-control custom-checkbox mr-sm-2">
        <input type="checkbox" class="custom-control-input" id="customControlAutosizing">
        <label class="custom-control-label" for="customControlAutosizing">Remember my preference</label>
      </div>
    </div>
    <div class="col-auto my-1">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
  </div>
</form>

内联式表单

使用 .form-inline样式在单个水平行上显示一系列标签,表单控件和按钮。内联表单中的表单控件与默认状态略有不同:

  • 基于display: flex控件组件,并允许您使用 间隙隔离flexbox 弹性布局样式。
  • 控制组件和input接受 width: auto 以覆盖预设的 width: 100%
  • 控制组件只会在viewport 576px宽度 时才会显示在行内,以便在移动设备上完整呈现。

你需要手机添加宽度或对齐在单个的控制元件上,通过 间隙隔离定义 (如下所示),最后一定要将 <label>包含在每个表单控制元件内,即使你需要使用 .sr-only从非正常屏幕访问它或隐藏它。

@
<form class="form-inline">
  <label class="sr-only" for="inlineFormInputName2">Name</label>
  <input type="text" class="form-control mb-2 mr-sm-2" id="inlineFormInputName2" placeholder="Jane Doe">

  <label class="sr-only" for="inlineFormInputGroupUsername2">Username</label>
  <div class="input-group mb-2 mr-sm-2">
    <div class="input-group-prepend">
      <div class="input-group-text">@</div>
    </div>
    <input type="text" class="form-control" id="inlineFormInputGroupUsername2" placeholder="Username">
  </div>

  <div class="form-check mb-2 mr-sm-2">
    <input class="form-check-input" type="checkbox" id="inlineFormCheck">
    <label class="form-check-label" for="inlineFormCheck">
      Remember me
    </label>
  </div>

  <button type="submit" class="btn btn-primary mb-2">Submit</button>
</form>

自定义表单和select选择控件也是支持的。

<form class="form-inline">
  <label class="my-1 mr-2" for="inlineFormCustomSelectPref">Preference</label>
  <select class="custom-select my-1 mr-sm-2" id="inlineFormCustomSelectPref">
    <option selected>Choose...</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
  </select>

  <div class="custom-control custom-checkbox my-1 mr-sm-2">
    <input type="checkbox" class="custom-control-input" id="customControlInline">
    <label class="custom-control-label" for="customControlInline">Remember my preference</label>
  </div>

  <button type="submit" class="btn btn-primary my-1">Submit</button>
</form>

隐藏的标签替代

如果您没有为每个input添加标签,屏幕阅读器等辅助技术将对您的表单有困难。对于这些内联表单,您可以使用.sr-only类隐藏标签。同时我们还提供了辅助技术标签以外的解决方法,例如: aria-labelaria-labelledbytitle 属性,如果这些都不存在,辅助技术可以使用 placeholder 的属性(如果它存在), 但注意:不推荐使用 placeholder替代其它标签方法。

表单下方帮助提示文本

可以使用..form-text t(以前称为.help-block 在v3中)创建表单中的块级帮助文本。可以使用任何内联HTML元素和通用样式(如.text-muted)灵活的展示帮助提示文本。

帮助提示文本需要与表单控件关联

帮助提示文本应该与使用该aria-describedby与表单控制元件相关联,这将确保辅助技术(如读屏器)在用户focus点中或input输入时了解此帮助提示文字。

input 下方的帮助文字可以用 .form-text.,包括 display: block并添加一些 margin-top以便与上面input框有所间隔。

Your password must be 8-20 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji.
<label for="inputPassword5">Password</label>
<input type="password" id="inputPassword5" class="form-control" aria-describedby="passwordHelpBlock">
<small id="passwordHelpBlock" class="form-text text-muted">
  Your password must be 8-20 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji.
</small>

行内也可以嵌入任意典型的HTML元素(无是<small><span>,或其它样式)。

Must be 8-20 characters long.
<form class="form-inline">
  <div class="form-group">
    <label for="inputPassword6">Password</label>
    <input type="password" id="inputPassword6" class="form-control mx-sm-3" aria-describedby="passwordHelpInline">
    <small id="passwordHelpInline" class="text-muted">
      Must be 8-20 characters long.
    </small>
  </div>
</form>

禁用表单

添加 disabled 布尔值属性到input上,就能防止使用者操作并看起来更灰淡。

<input class="form-control" id="disabledInput" type="text" placeholder="Disabled input here..." disabled>

Add the disabled attribute to a <fieldset> to disable all the controls within.

<form>
  <fieldset disabled>
    <div class="form-group">
      <label for="disabledTextInput">Disabled input</label>
      <input type="text" id="disabledTextInput" class="form-control" placeholder="Disabled input">
    </div>
    <div class="form-group">
      <label for="disabledSelect">Disabled select menu</label>
      <select id="disabledSelect" class="form-control">
        <option>Disabled select</option>
      </select>
    </div>
    <div class="form-check">
      <input class="form-check-input" type="checkbox" id="disabledFieldsetCheck" disabled>
      <label class="form-check-label" for="disabledFieldsetCheck">
        Can't check this
      </label>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </fieldset>
</form>

附加说明与锚

默认情况下,浏览器会将<fieldset disabled>中所有的表单控制项(<input><select><button> 元素) 视为禁用,以防止键盘鼠标与它们发生交互,但是如果你的表单还包含了 <a ... class="btn btn-*"> 元素,则只会给出一种pointer-events: none的样式,关于按钮禁用(特别是 btn按钮禁用状态 (特别是在提交元素的子部份), 此CSS属性尚未标准化(被各浏览器厂商广泛支持),Opera 18及更低版本或IE10中完全不兼容,并且不会阻止健盘使用者focus或启动这些链接。为了安全起见,请自行使用自定义JavaScript来禁用这些链接。

跨浏览器兼容性支持

虽然Bootstrap会在所有的浏览器应用这些样式,但是Internet Explorer 11 及更低版本IE不完全支持<fieldset>标签上的disabled 属性,故在IE中请使用自定义JavaScript 脚本来禁用标签(已经不存在IE12,未来的IE已更名Edge浏览器-译者注)。

验证

通过HTNML5表音验证可以在我们支持的浏览器中为你的用户提供可操作的反馈。从浏览器中选择默认的验证反馈,或者使用我们内置的Class样式和启动JavaScript实现自定义消息。

我们强烈推荐使用自定义方式-因为浏览器默认不会向屏幕阅读者提供友好反馈。

运行原理

Bootstrap中验证机制如下:

  • HTML表单验证通过CSS的两个伪类应用::invalid以及:valid。它适用于 <input><select><textarea>元素。
  • Bootstrap ::invalid:valid 樣式在 .was-validated ,通常会反馈到<form>,否则必填的内容在加载的过程中会显示无效,这个方法你呆以选择在任何时候启用它(通过是在尝试提交表单后。
  • 作为备用,.is-invalid.is-valid类别可以用来代替伪类用于服务器端验证。他们不需要.server side validation定义在父层上。
  • 由于CSS的工作原理限制,我们无法(现在)将样式应用于DOM中的表单控制组件之前的<label>上,而不需要使用自用自定义JavaScript。
  • 所有现代浏览器都支持约束验证API,这是一系列用于验证表单控件的JavaScript方法。
  • 反馈消息可能会使用浏览器默认值(每个浏览器不同,通过私有CSS样式)或其他HTML和CSS的自定义反馈样式。
  • 你可以在JavaScript中 使用setCustomValidity 提供有效自定义消息。

请参与以下的自定义表单验证样式、服务器端验证Class和浏览器默认值。

自定义样式

对于自定义Bootstrap表单验证消息,您需要将 novalidate属性添加到您的<form>。这将禁用浏览器默认的反馈工具提示,但仍提供对JavaScript中的表单验证API有效支持。尝试提交以下表格; 我们的JavaScript将拦截提交按钮并向您传递反馈:

尝试提交时,您将看到:invalid:valid的样式应用于表单控件。

When attempting to submit, you’ll see the styles applied to your form controls.

Looks good!
Looks good!
@
Please choose a username.
Please provide a valid city.
Please provide a valid state.
Please provide a valid zip.
You must agree before submitting.
<form class="needs-validation" novalidate>
  <div class="form-row">
    <div class="col-md-4 mb-3">
      <label for="validationCustom01">First name</label>
      <input type="text" class="form-control" id="validationCustom01" placeholder="First name" value="Mark" required>
      <div class="valid-feedback">
        Looks good!
      </div>
    </div>
    <div class="col-md-4 mb-3">
      <label for="validationCustom02">Last name</label>
      <input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="Otto" required>
      <div class="valid-feedback">
        Looks good!
      </div>
    </div>
    <div class="col-md-4 mb-3">
      <label for="validationCustomUsername">Username</label>
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" id="inputGroupPrepend">@</span>
        </div>
        <input type="text" class="form-control" id="validationCustomUsername" placeholder="Username" aria-describedby="inputGroupPrepend" required>
        <div class="invalid-feedback">
          Please choose a username.
        </div>
      </div>
    </div>
  </div>
  <div class="form-row">
    <div class="col-md-6 mb-3">
      <label for="validationCustom03">City</label>
      <input type="text" class="form-control" id="validationCustom03" placeholder="City" required>
      <div class="invalid-feedback">
        Please provide a valid city.
      </div>
    </div>
    <div class="col-md-3 mb-3">
      <label for="validationCustom04">State</label>
      <input type="text" class="form-control" id="validationCustom04" placeholder="State" required>
      <div class="invalid-feedback">
        Please provide a valid state.
      </div>
    </div>
    <div class="col-md-3 mb-3">
      <label for="validationCustom05">Zip</label>
      <input type="text" class="form-control" id="validationCustom05" placeholder="Zip" required>
      <div class="invalid-feedback">
        Please provide a valid zip.
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="form-check">
      <input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
      <label class="form-check-label" for="invalidCheck">
        Agree to terms and conditions
      </label>
      <div class="invalid-feedback">
        You must agree before submitting.
      </div>
    </div>
  </div>
  <button class="btn btn-primary" type="submit">Submit form</button>
</form>

<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
  'use strict';
  window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
</script>

浏览器默认值

Not interested in custom validation feedback messages or writing JavaScript to change form behaviors? All good, you can use the browser defaults. Try submitting the form below. Depending on your browser and OS, you’ll see a slightly different style of feedback.

While these feedback styles cannot be styled with CSS, you can still customize the feedback text through JavaScript.

@
<form>
  <div class="form-row">
    <div class="col-md-4 mb-3">
      <label for="validationDefault01">First name</label>
      <input type="text" class="form-control" id="validationDefault01" placeholder="First name" value="Mark" required>
    </div>
    <div class="col-md-4 mb-3">
      <label for="validationDefault02">Last name</label>
      <input type="text" class="form-control" id="validationDefault02" placeholder="Last name" value="Otto" required>
    </div>
    <div class="col-md-4 mb-3">
      <label for="validationDefaultUsername">Username</label>
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" id="inputGroupPrepend2">@</span>
        </div>
        <input type="text" class="form-control" id="validationDefaultUsername" placeholder="Username" aria-describedby="inputGroupPrepend2" required>
      </div>
    </div>
  </div>
  <div class="form-row">
    <div class="col-md-6 mb-3">
      <label for="validationDefault03">City</label>
      <input type="text" class="form-control" id="validationDefault03" placeholder="City" required>
    </div>
    <div class="col-md-3 mb-3">
      <label for="validationDefault04">State</label>
      <input type="text" class="form-control" id="validationDefault04" placeholder="State" required>
    </div>
    <div class="col-md-3 mb-3">
      <label for="validationDefault05">Zip</label>
      <input type="text" class="form-control" id="validationDefault05" placeholder="Zip" required>
    </div>
  </div>
  <div class="form-group">
    <div class="form-check">
      <input class="form-check-input" type="checkbox" value="" id="invalidCheck2" required>
      <label class="form-check-label" for="invalidCheck2">
        Agree to terms and conditions
      </label>
    </div>
  </div>
  <button class="btn btn-primary" type="submit">Submit form</button>
</form>

服务器端

我们建议使用客户端验证,但是如果您需要使用服务器端验证,则可以使用..is-invalid.is-valid来表示无效和有效的表单字段。注意,.invalid-feedback这些类也支持。

Looks good!
Looks good!
@
Please choose a username.
Please provide a valid city.
Please provide a valid state.
Please provide a valid zip.
You must agree before submitting.
<form>
  <div class="form-row">
    <div class="col-md-4 mb-3">
      <label for="validationServer01">First name</label>
      <input type="text" class="form-control is-valid" id="validationServer01" placeholder="First name" value="Mark" required>
      <div class="valid-feedback">
        Looks good!
      </div>
    </div>
    <div class="col-md-4 mb-3">
      <label for="validationServer02">Last name</label>
      <input type="text" class="form-control is-valid" id="validationServer02" placeholder="Last name" value="Otto" required>
      <div class="valid-feedback">
        Looks good!
      </div>
    </div>
    <div class="col-md-4 mb-3">
      <label for="validationServerUsername">Username</label>
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" id="inputGroupPrepend3">@</span>
        </div>
        <input type="text" class="form-control is-invalid" id="validationServerUsername" placeholder="Username" aria-describedby="inputGroupPrepend3" required>
        <div class="invalid-feedback">
          Please choose a username.
        </div>
      </div>
    </div>
  </div>
  <div class="form-row">
    <div class="col-md-6 mb-3">
      <label for="validationServer03">City</label>
      <input type="text" class="form-control is-invalid" id="validationServer03" placeholder="City" required>
      <div class="invalid-feedback">
        Please provide a valid city.
      </div>
    </div>
    <div class="col-md-3 mb-3">
      <label for="validationServer04">State</label>
      <input type="text" class="form-control is-invalid" id="validationServer04" placeholder="State" required>
      <div class="invalid-feedback">
        Please provide a valid state.
      </div>
    </div>
    <div class="col-md-3 mb-3">
      <label for="validationServer05">Zip</label>
      <input type="text" class="form-control is-invalid" id="validationServer05" placeholder="Zip" required>
      <div class="invalid-feedback">
        Please provide a valid zip.
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="form-check">
      <input class="form-check-input is-invalid" type="checkbox" value="" id="invalidCheck3" required>
      <label class="form-check-label" for="invalidCheck3">
        Agree to terms and conditions
      </label>
      <div class="invalid-feedback">
        You must agree before submitting.
      </div>
    </div>
  </div>
  <button class="btn btn-primary" type="submit">Submit form</button>
</form>

支持元素

示例表单显示了其中的原生文本 <input>定义,但也可为自定义表单控件提供表单验证样式。

Example invalid feedback text
More example invalid feedback text
Example invalid custom select feedback
Example invalid custom file feedback
<form class="was-validated">
  <div class="custom-control custom-checkbox mb-3">
    <input type="checkbox" class="custom-control-input" id="customControlValidation1" required>
    <label class="custom-control-label" for="customControlValidation1">Check this custom checkbox</label>
    <div class="invalid-feedback">Example invalid feedback text</div>
  </div>

  <div class="custom-control custom-radio">
    <input type="radio" class="custom-control-input" id="customControlValidation2" name="radio-stacked" required>
    <label class="custom-control-label" for="customControlValidation2">Toggle this custom radio</label>
  </div>
  <div class="custom-control custom-radio mb-3">
    <input type="radio" class="custom-control-input" id="customControlValidation3" name="radio-stacked" required>
    <label class="custom-control-label" for="customControlValidation3">Or toggle this other custom radio</label>
    <div class="invalid-feedback">More example invalid feedback text</div>
  </div>

  <div class="form-group">
    <select class="custom-select" required>
      <option value="">Open this select menu</option>
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>

    </select>
    <div class="invalid-feedback">Example invalid custom select feedback</div>
  </div>

  <div class="custom-file">
    <input type="file" class="custom-file-input" id="validatedCustomFile" required>
    <label class="custom-file-label" for="validatedCustomFile">Choose file...</label>
    <div class="invalid-feedback">Example invalid custom file feedback</div>
  </div>
</form>

提示

如果表单布局允许,则可以交换。.{valid | invalid} --tooltip 类的。.{valid|invalid}-tooltip 以在样式化的工具提示中显示验证反馈。 确保有一个父母的位置:相对工具提示定位。 在下面的例子中,我们的列类已经有了,但是你的项目可能需要一个替代的设置。

Looks good!
Looks good!
@
Please choose a unique and valid username.
Please provide a valid city.
Please provide a valid state.
Please provide a valid zip.
<form class="needs-validation" novalidate>
  <div class="form-row">
    <div class="col-md-4 mb-3">
      <label for="validationTooltip01">First name</label>
      <input type="text" class="form-control" id="validationTooltip01" placeholder="First name" value="Mark" required>
      <div class="valid-tooltip">
        Looks good!
      </div>
    </div>
    <div class="col-md-4 mb-3">
      <label for="validationTooltip02">Last name</label>
      <input type="text" class="form-control" id="validationTooltip02" placeholder="Last name" value="Otto" required>
      <div class="valid-tooltip">
        Looks good!
      </div>
    </div>
    <div class="col-md-4 mb-3">
      <label for="validationTooltipUsername">Username</label>
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" id="validationTooltipUsernamePrepend">@</span>
        </div>
        <input type="text" class="form-control" id="validationTooltipUsername" placeholder="Username" aria-describedby="validationTooltipUsernamePrepend" required>
        <div class="invalid-tooltip">
          Please choose a unique and valid username.
        </div>
      </div>
    </div>
  </div>
  <div class="form-row">
    <div class="col-md-6 mb-3">
      <label for="validationTooltip03">City</label>
      <input type="text" class="form-control" id="validationTooltip03" placeholder="City" required>
      <div class="invalid-tooltip">
        Please provide a valid city.
      </div>
    </div>
    <div class="col-md-3 mb-3">
      <label for="validationTooltip04">State</label>
      <input type="text" class="form-control" id="validationTooltip04" placeholder="State" required>
      <div class="invalid-tooltip">
        Please provide a valid state.
      </div>
    </div>
    <div class="col-md-3 mb-3">
      <label for="validationTooltip05">Zip</label>
      <input type="text" class="form-control" id="validationTooltip05" placeholder="Zip" required>
      <div class="invalid-tooltip">
        Please provide a valid zip.
      </div>
    </div>
  </div>
  <button class="btn btn-primary" type="submit">Submit form</button>
</form>

自定义表单

为了使自定义表单和跨浏览器保持一致性,请使用自定义的表单元素来替换浏览器的默认值,它们建立在语义和具备友了的标记之上,因此它们是可以替代任何默认表单控制元件的。

复选框和单选框自定义

每个选取块和选项按钮被包在一个 <label>中,因为理由有三:

  • 这样能提供更大的点击区域。
  • 这样能提供一个更加有意义的语义容器,以帮助我们替换默认的<input>组件。
  • 这样会自动触发 <input> 的状态,省去引用JavaScript 插件。

我们使用opacity 隐藏默认的<input>并使用.custom-control-indicator在它的位置之上构建一个全新的表单指示器,遗憾的是,由于CSS的content对该元素不起作用,所以我们不能仅使用<input>构建一个自定义事件。

我们使用(~)CSS兄弟选择器来为<input>处理样式和状态,就象 :checked自定义窗体指示符一样,当与 .custom-control-description 结合使用,也可以根据<input>的状态对每个对象进行样式调整。

在检查状态下,我们使用 Open Iconicbase64 embedded SVG icons图标,,提供跨浏览器和样式设计的最佳控制器。

Checkbox勾选

<div class="custom-control custom-checkbox">
  <input type="checkbox" class="custom-control-input" id="customCheck1">
  <label class="custom-control-label" for="customCheck1">Check this custom checkbox</label>
</div>

通过JavaScript(当没有可用的HTML属性来指定它)手机设置时,自定义勾选控件还可以使用 :indeterminate 伪类(实现一种模糊的提示使用的样式),可见bbs.z01.com/PItem?ID=15849

如果你正使用 jQuery,可以用下面方法:

$('.your-checkbox').prop('indeterminate', true)

单选项

<div class="custom-control custom-radio">
  <input type="radio" id="customRadio1" name="customRadio" class="custom-control-input">
  <label class="custom-control-label" for="customRadio1">Toggle this custom radio</label>
</div>
<div class="custom-control custom-radio">
  <input type="radio" id="customRadio2" name="customRadio" class="custom-control-input">
  <label class="custom-control-label" for="customRadio2">Or toggle this other custom radio</label>
</div>

一致

<div class="custom-control custom-radio custom-control-inline">
	  <input type="radio" id="customRadioInline1" name="customRadioInline1" class="custom-control-input">
	  <label class="custom-control-label" for="customRadioInline1">Toggle this custom radio</label>
	</div>
	<div class="custom-control custom-radio custom-control-inline">
	  <input type="radio" id="customRadioInline2" name="customRadioInline1" class="custom-control-input">
	  <label class="custom-control-label" for="customRadioInline2">Or toggle this other custom radio</label>
	</div>

禁用

自定义单选框和多选框也可以禁用,只要将 disabled 布尔值属性加入到 <input> ,禁用的指示和样式都会自动载入。

<div class="custom-control custom-checkbox">
  <input type="checkbox" class="custom-control-input" id="customCheckDisabled" disabled>
  <label class="custom-control-label" for="customCheckDisabled">Check this custom checkbox</label>
</div>

<div class="custom-control custom-radio">
  <input type="radio" id="radio3" name="radioDisabled" id="customRadioDisabled" class="custom-control-input" disabled>
  <label class="custom-control-label" for="customRadioDisabled">Toggle this custom radio</label>
</div>

堆叠

自訂的核取方塊和單選按鈕原本會以行內樣式排列。加入一個 .custom-controls-stacked 的父級,以確保每個表單控制元件在不同的列上。 自定义的单选框和复选框,原本会以行内样式水平排列,加入一个 .custom-controls-stacked 父级,则可以确保每个控件在不同的行上,形成堆叠效果。

<div class="custom-controls-stacked">
  <label class="custom-control custom-radio">
    <input id="radioStacked3" name="radio-stacked" type="radio" class="custom-control-input">
    <span class="custom-control-indicator"></span>
    <span class="custom-control-description">Toggle this custom radio</span>
  </label>
  <label class="custom-control custom-radio">
    <input id="radioStacked4" name="radio-stacked" type="radio" class="custom-control-input">
    <span class="custom-control-indicator"></span>
    <span class="custom-control-description">Or toggle this other custom radio</span>
  </label>
</div>

Select menu下拉选择菜单

自定义<select>下拉选择菜单只需要一个.custom-selectCSS即可触发自定义样式。

<select class="custom-select">
  <option selected>Open this select menu</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

您也可以选择小和大的自定义选择来匹配我们相似大小的文本输入。

<select class="custom-select custom-select-lg mb-3">
	  <option selected>Open this select menu</option>
	  <option value="1">One</option>
	  <option value="2">Two</option>
	  <option value="3">Three</option>
	</select>

	<select class="custom-select custom-select-sm">
	  <option selected>Open this select menu</option>
	  <option value="1">One</option>
	  <option value="2">Two</option>
	  <option value="3">Three</option>
	</select>

多重属性也被支持:

<select class="custom-select" multiple>
  <option selected>Open this select menu</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

size 属性:

<select class="custom-select" size="3">
  <option selected>Open this select menu</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

范围

创建自定义<input type="range">与控制.custom-range。轨道(背景)和大拇指(值)都被设置为跨浏览器显示相同。由于只有IE和Firefox支持从拇指的左侧或右侧“填充”它们的轨迹,以作为视觉指示进度的手段,所以我们目前不支持它。

<label for="customRange1">Example range</label>
<input type="range" class="custom-range" id="customRange1">

范围输入分别具有minmax- 0和的隐含值100。您可以为那些使用minmax属性指定新值。

<label for="customRange2">Example range</label>
<input type="range" class="custom-range" min="0" max="5" id="customRange2">

默认情况下,范围输入“捕捉”为整数值。要改变这一点,你可以指定一个step 值。在下面的例子中,我们使用了两倍的步数step="0.5"

<label for="customRange3">Example range</label>
<input type="range" class="custom-range" min="0" max="5" step="0.5" id="customRange3">

文件浏览(文件选取)器

文件浏览(选取)是比较原始粗糙的,它需要额外的JavaScript定义支持,如果你将Choose file…文件选取和所选文件的名称关联。

<div class="custom-file">
  <input type="file" class="custom-file-input" id="customFile">
  <label class="custom-file-label" for="customFile">Choose file</label>
</div>

Here’s how it works:

  • We wrap the <input> in a <label> so the custom control properly triggers the file browser.
  • We hide the default file <input> via opacity.
  • We use ::after to generate a custom background and directive (Choose file…).
  • We use ::before to generate and position the Browse button.
  • We declare a height on the <input> for proper spacing for surrounding content.

In other words, it’s an entirely custom element, all generated via CSS.

Translating or customizing the strings

The :lang() pseudo-class is used to allow for easy translation of the “Browse” and “Choose file…” text into other languages. Simply override or add entries to the $custom-file-text SCSS variable with the relevant language tag and localized strings. The English strings can be customized the same way. For example, here’s how one might add a Spanish translation (Spanish’s language code is es):

$custom-file-text: (
  en: "Browse",
  es: "Elegir"
);

Here’s lang(es) in action on the custom file input for a Spanish translation:

<div class="custom-file">
  <input type="file" class="custom-file-input" id="customFileLang" lang="es">
  <label class="custom-file-label" for="customFileLang">Seleccionar Archivo</label>
</div>

You’ll need to set the language of your document (or subtree thereof) correctly in order for the correct text to be shown. This can be done using the lang attribute or the Content-Language HTTP header, among other methods.