bootstrap组件
In this article, you’ll learn how to style form elements with the Bootstrap form component, and how to take advantage of the grid system to align these elements. Also, we’ll see horizontal and inline forms in action, as well as discuss form validation.
在本文中,您将学习如何使用Bootstrap表单组件为表单元素设置样式,以及如何利用网格系统对齐这些元素。 此外,我们还将看到实际使用的水平和内联表单,并讨论表单验证。
I still remember the (not so good) old days when we had to code all the styling for websites manually. There were very few solid CSS solutions, and creating complex UIs used to be a huge pain. It was like an arcane lore that developers were sharing with each other: they told tales on how to make rounded circles, how to highlight focused elements or create a gradient background … I don’t really miss those days. Luckily, there are many new technologies out there that help us to speed the process of styling web applications. One such technology is Bootstrap, and today we will discuss one of its most-used component: forms.
我仍然记得(不是很好)过去的日子,那时我们不得不手动编写网站的所有样式。 几乎没有可靠CSS解决方案,创建复杂的UI曾经是一个巨大的痛苦。 开发人员之间相互交流就像是一种神秘的知识:他们讲述了如何制作圆形圆圈,如何突出显示聚焦的元素或创建渐变背景的故事……我真的不错过那些日子。 幸运的是,有许多新技术可以帮助我们加快Web应用程序样式的过程。 Bootstrap是一种这样的技术,今天我们将讨论其最常用的组件之一: Forms 。
There are loads of predefined styles that can be applied to forms, and by using them you can create fancy UIs with little effort.
有许多预定义样式可以应用于表单,通过使用它们,您可以毫不费力地创建精美的UI。
入门 (Getting Started)
If you’d like to follow along, create the following boilerplate HTML:
如果您想继续,请创建以下样板HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container">
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</body>
</html>
We load the Bootstrap’s styles and some scripts that will be required in one of the examples. This is it! All the markup should be placed inside the container
block that acts as a main element for our page.
我们加载Bootstrap的样式和示例之一中所需的一些脚本。 就是这个! 所有标记都应放置在充当页面主要元素的container
块内。
We can proceed to the next section and start crafting our first form.
我们可以继续下一节并开始制作我们的第一个表格。
创建一个简单的表格 (Creating a Simple Form)
Suppose we’re creating a registration form for our new shiny website. Our form should provide, at the very least, fields for an email address and a password:
假设我们正在为新的闪亮网站创建注册表。 我们的表格至少应提供电子邮件地址和密码的字段:
<div class="container">
<p class="h1">Register</p>
<form>
<label for="email">Email address</label>
<input type="email" id="email" placeholder="Enter email">
<label for="password">Password</label>
<input type="password" id="password" placeholder="Password">
</form>
</div>
Now let’s style these fields a bit. First and foremost, the label
and input
should be wrapped inside an element with the Bootstrap form component form-group
class, which is going to add a small top margin. Also, we assign a form-control
class to the inputs to make them look nicer:
现在让我们对这些字段进行一些样式设置。 首先, label
和input
应该使用Bootstrap表单组件form-group
类包装在一个元素内,这将增加一个小的顶部边距。 另外,我们为输入分配一个form-control
类,以使其看起来更好:
<form>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" id="email" placeholder="Enter email" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" placeholder="Password" class="form-control">
</div>
</form>
Note that Bootstrap automatically reboots form elements so that the new styles can be applied easily.
请注意,Bootstrap会自动重新引导表单元素,以便可以轻松应用新样式。
Why don’t we also display some help text beneath the email form to inform users that we won’t be using their data in any malicious way? In Bootstrap 3, help text is marked with the help-block
class, but the latest release of the framework uses a class called form-text
. Let’s place it right beneath the input
(inside the form-group
). Also, let’s make the text look more subtle by applying the Bootstrap form component text-muted
class:
为什么我们还不在电子邮件表单下方显示一些帮助文本 ,以告知用户我们不会以任何恶意方式使用其数据? 在Bootstrap 3中,帮助文本用help-block
类标记,但是该框架的最新版本使用称为form-text
的类。 让我们将其放置在input
下方(在form-group
)。 另外,通过应用Bootstrap表单组件的text-muted
类,使文本看起来更加微妙:
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control"
id="email" aria-describedby="emailHelp" placeholder="Enter email"> <!-- #1 -->
<small id="emailHelp" class="form-text text-muted"> <!-- #2 -->
For authentication purposes only. We will never share your email with anyone!
</small>
</div>
Note how we added the aria-describedby
attribute (point #1) for the input to explain that this field is being described by our help block (#2).
请注意,我们如何为输入添加aria-describedby
属性(点#1),以说明我们的帮助块(#2)正在描述此字段。
Why don’t we also make our two fields a bit larger to emphasize their importance? Inputs can be easily sized with the Bootstrap form component’s form-control-lg
and form-control-sm
classes:
我们为什么不同时扩大两个领域以强调它们的重要性? 可以使用Bootstrap表单组件的form-control-lg
和form-control-sm
类轻松调整输入的大小 :
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control form-control-lg"
id="email" aria-describedby="emailHelp" placeholder="Enter email"> <!-- #1 -->
<small id="emailHelp" class="form-text text-muted">
For authentication purposes only. We will never share your email with anyone!
</small>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control form-control-lg"
id="password" placeholder="Password"> <!-- #2 -->
</div>
Here’s the result:
结果如下:
The form looks very clear, and the currently selected input gets a nice blue border. Cool!
表单看起来非常清晰,并且当前选择的输入带有漂亮的蓝色边框。 凉!
Bootstrap表单组件只读元素 (Bootstrap Form Component Read-only Elements)
Suppose now we’d like to introduce multiple pricing plans for our users, but at the moment only a “Basic” plan is available. Let’s add a Bootstrap form component read-only input styled as plain text. It’s as simple as assigning the form-control-plaintext
class:
假设现在我们想为我们的用户引入多种定价计划,但是目前只有“基本”计划可用。 让我们添加一个样式为纯文本的Bootstrap表单组件只读输入 。 就像分配form-control-plaintext
类一样简单:
<div class="form-group">
<label for="pricingPlan">Pricing plan</label>
<input type="text" readonly class="form-control-plaintext"
id="pricingPlan" value="Basic" aria-describedby="pricingPlanHelp"> <!-- #1 -->
<small id="pricingPlanHelp" class="form-text text-muted">
Basic is the only plan so far, but we'll introduce more soon!
</small>
</div>
Here’s the result:
结果如下:
引导表单组件支持的其他类型的输入 (Other Types of Input Supported by the Bootstrap Form Component)
Bootstrap supports styling for inputs of all types. For example, we may opt for a dropdown to allow users to choose their role:
Bootstrap支持所有类型输入的样式。 例如,我们可以选择一个下拉菜单,以允许用户选择其角色:
<div class="form-group">
<label for="role">Your role</label>
<select class="form-control" id="role">
<option>Developer</option>
<option>Designer</option>
<option>Manager</option>
</select>
</div>
Once again, we’re simply wrapping everything inside a container with the Bootstrap form component form-group
class and assigning the form-control
class to the dropdown.
再一次,我们只是使用Bootstrap表单组件form-group
类将所有内容包装在容器中,然后将form-control
类分配给下拉列表。
What about the textarea
? We just follow the same principle:
那textarea
呢? 我们只是遵循相同的原则:
<div class="form-group">
<label for="comments">Comments (optional)</label>
<textarea class="form-control" id="comments" rows="3"></textarea>
</div>
File uploading control? No problem here either:
文件上传控制? 这里也没问题:
<div class="form-group">
<label for="photo">Your photo</label>
<input type="file" class="form-control-file" id="photo">
</div>
Checkboxes? Easy! The only thing to remember is that checkboxes and radios should be wrapped inside an element with the form-check
, not form-group
, class. This class adds some extra padding to make these elements look nicer. Also, we assign form-check-input
(#1) to the checkbox and form-check-label
(#2) to the label so that they are aligned properly:
复选框? 简单! 唯一要记住的是,复选框和单选框应使用form-check
(而不是form-group
)类包装在元素内。 此类添加了一些额外的填充,以使这些元素看起来更好。 另外,我们将form-check-input
(#1)分配给复选框,并将form-check-label
(#2)分配给标签,以便它们正确对齐:
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="userAgreement"> <!-- #1 -->
<label class="form-check-label" for="userAgreement"> <!-- #2 -->
I accept <a href="#">user agreement</a>
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="newsletter">
<label class="form-check-label" for="newsletter">
I'd like to receive newsletters
</label>
</div>
Let’s reload the page and observe the result:
让我们重新加载页面并观察结果:
Looking quite nice for a page that has no custom styles at all.
完全没有自定义样式的页面看起来非常不错。
纽扣 (Buttons)
Next, we’re going to add a Submit and a Back button to the bottom of the form. Buttons can be styled with Bootstrap as well: there’s a variety of available colors, sizes and states to choose from.
接下来,我们将在表单底部添加一个Submit和一个Back按钮。 也可以使用Bootstrap设置按钮样式:有多种可用的颜色 , 大小和状态可供选择。
Interestingly, predefined classes don’t work just with buttons. For example, a link may act as a button and can be styled as such using the same classes. At the very least, the element should be assigned a class of btn
:
有趣的是,预定义的类并不仅仅适用于按钮。 例如,链接可以充当按钮,并可以使用相同的类进行样式设置。 至少,应该为元素分配btn
类:
<!-- other form elements go here... -->
<div class="mt-3">
<button type="submit" class="btn">Register!</button>
<a href="#" class="btn">Back</a>
</div>
mt-3
sets a small top margin for our buttons. The Register! button is obviously the main star, so we’re going to mark it as primary and make it larger. The Back link doesn’t have to attract all the attention, so we’ll style it as a button link:
mt-3
为我们的按钮设置了很小的顶部边距 。 注册! 按钮显然是主要的星形,因此我们将其标记为主要并使其更大。 Back链接不必吸引所有的注意力,因此我们将其设置为按钮链接:
<div class="mt-3">
<button type="submit" class="btn btn-primary btn-lg">Register!</button>
<a href="#" class="btn btn-link">Back</a>
</div>
Now, the primary button visually stands out thanks to the blue background:
现在,由于蓝色背景,主按钮在视觉上脱颖而出:
If you don’t like this background, the button can also be styled as outlined with the help of btn-outline-*
classes:
如果您不喜欢这种背景,还可以借助btn-outline-*
类来概述按钮的样式:
<button type="submit" class="btn btn-outline-primary btn-lg">Register!</button>
输入组 (Input Groups)
Another cool feature of Bootstrap is input groups. Let’s say we want to allow users to choose their unique profile URL looking like http://SUBDOMAIN.PROFILE.example.com
, where:
Bootstrap的另一个很酷的功能是输入组 。 假设我们要允许用户选择其唯一的个人资料网址,例如http://SUBDOMAIN.PROFILE.example.com
,其中:
SUBDOMAIN
is eithermy.
,private.
, orown.
SUBDOMAIN
是my.
,private.
或own.
PROFILE
is defined by the user.PROFILE
由用户定义。
So, the URL might be http://my.superpage.example.com
or http://private.dashboard.example.com
. Of course, we can provide a basic text input and say something like “Enter your unique profile name”, but the user might not understand what’s going on. Instead, we want to offer a visual example of how this profile name is going to be used.
因此,URL可能是http://my.superpage.example.com
或http://private.dashboard.example.com
。 当然,我们可以提供基本的文本输入,并说诸如“输入您的唯一配置文件名称”之类的内容,但是用户可能不了解发生了什么。 相反,我们想提供一个视觉示例,说明如何使用此配置文件名称。
In order to do this, we’ll provide additional help to the text input in the following way:
为此,我们将通过以下方式为文本输入提供其他帮助:
<div class="form-group">
<label for="profileUrl">Your profile URL</label>
<div class="input-group mb-3"> <!-- #1 -->
<div class="input-group-prepend"> <!-- #2 -->
<span class="input-group-text">http://</span> <!-- #3 -->
<button class="btn btn-outline-secondary dropdown-toggle"> <!-- #4 -->
type="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">my.</button>
<div class="dropdown-menu"> <!-- #5 -->
<a class="dropdown-item" href="#">private.</a>
<a class="dropdown-item" href="#">own.</a>
</div>
</div>
<input type="text" id="profileUrl" class="form-control">
<div class="input-group-append"> <!-- #6 -->
<span class="input-group-text">.example.com</span>
</div>
</div>
</div>
Let’s walk through the code above step by step:
让我们逐步介绍上面的代码:
- #1. This is where our input group opens. Each input group contains an input and one or more “add-ons” to be placed before or after this input. #1。 这是我们的输入组打开的地方。 每个输入组包含一个输入和一个或多个“附加”,分别在此输入之前或之后。
- #2. We’re prepending two elements to our text input. #2。 我们在文本输入之前添加了两个元素。
#3. This is going to display an add-on with the
http://
text.#3。 这将显示带有
http://
文本的加载项。#4. Here things become a bit more complex. We’re displaying a button with a text “my.” (which is our subdomain). When this button is clicked, a dropdown is displayed with two other options: ”private.” and ”own.”. Don’t forget that the dropdown relies on JavaScript, so make sure you’ve hooked up all the necessary scripts as explained at the beginning of this article.
#4。 在这里事情变得更加复杂。 我们正在显示带有文本“我”的按钮。 (这是我们的子域)。 单击此按钮后,将显示一个下拉菜单 ,其中包含两个其他选项:“私人”。 和“拥有”。 不要忘记下拉列表依赖于JavaScript,因此请确保已按照本文开头的说明连接了所有必需的脚本。
#5. That’s the actual dropdown menu, initially hidden. It may be further styled as explained by the docs.
#5。 那是实际的下拉菜单,最初是隐藏的。 可以按照docs的说明进一步设置样式。
#6. This
div
with the class ofinput-group-append
represents the last add-on that should be appended to the text input.#6。 带有
input-group-append
类的div
代表应该附加到文本输入的最后一个附加组件。
Whew! As a result, we’ve achieved the following piece of UI:
ew! 结果,我们实现了以下用户界面:
Looking quite nice and, what’s more important, our users will understand right away what this input is for!
看起来非常不错,更重要的是,我们的用户将立即理解此输入的用途!
This wraps up the first section of this article. You may find the final result on CodePen:
这总结了本文的第一部分。 您可以在CodePen上找到最终结果:
See the Pen Sitepoint Bootstrap 4 Simple Form by SitePoint (@SitePoint) on CodePen.
请参阅CodePen上的SitePoint ( @SitePoint )提供的Pen Sitepoint Bootstrap 4简单表格 。
带网格的表格 (Forms With Grid)
全部关于行和列 (It’s All About Rows and Columns)
Another quite common task is to make forms more compact by placing multiple inputs on the same row. This can be done using the Bootstrap form component form grid system, which relies on Bootstrap’s generic grid.
另一个非常常见的任务是通过在同一行上放置多个输入来使表单更紧凑。 这可以使用Bootstrap表单组件表单网格系统来完成,该系统依赖于Bootstrap的通用网格 。
To place multiple inputs and labels on the same row, our form groups should be wrapped with either the Bootstrap form component’s row
or form-row
(the only difference is that the latter class adds smaller gutters between the columns). Next, we assign the col-{viewport}-{columns}
class to the form groups themselves. For instance, that’s how we can modify the first three groups from the registration form created in the previous section:
要将多个输入和标签放在同一行上,我们的表单组应该用Bootstrap表单组件的row
或form-row
进行包装(唯一的区别是后者的类在列之间添加了较小的装订线)。 接下来,我们将col-{viewport}-{columns}
类分配给表单组本身 。 例如,这就是我们可以从上一部分中创建的注册表格中修改前三个组的方式:
<div class="form-row"> <!-- #1 -->
<div class="form-group col-sm-4"> <!-- #2 -->
<label for="email">Email address</label>
<input type="email" class="form-control form-control-lg"
id="email" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">
For authentication purposes only. We will never share your email with anyone!
</small>
</div>
<div class="form-group col-sm-4">
<label for="password">Password</label>
<input type="password" class="form-control form-control-lg"
id="password" placeholder="Password">
</div>
<div class="form-group col-sm-4">
<label for="pricingPlan">Pricing plan</label>
<input type="text" readonly class="form-control-plaintext"
id="pricingPlan" value="Basic" aria-describedby="pricingPlanHelp">
<small id="pricingPlanHelp" class="form-text text-muted">
Basic is the only plan so far, but we'll introduce more soon!
</small>
</div>
</div>
Take a look at the result:
看一下结果:
For very small viewports, these groups will be stacked on top of each other.
对于非常小的视口,这些组将彼此堆叠。
We then proceed to the pricing plan and profile URL. The latter group probably requires quite a lot of space, so let’s use an md
(medium viewport) breakpoint in this case:
然后,我们继续进行定价计划和配置文件URL。 后一组可能需要很多空间,因此在这种情况下,我们使用md
(中等视口)断点:
<div class="form-row"> <!-- #1 -->
<div class="form-group col-md-4"> <!-- #2 -->
<label for="role">Your role</label>
<select class="form-control" id="role">
<option>Developer</option>
<option>Designer</option>
<option>Manager</option>
</select>
</div>
<div class="form-group col-md-8"> <!-- #3 -->
<label for="profileUrl">Your profile URL</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">http://</span>
<button class="btn btn-outline-secondary dropdown-toggle"
type="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">my.</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">private.</a>
<a class="dropdown-item" href="#">own.</a>
</div>
</div>
<input type="text" id="profileUrl" class="form-control">
<div class="input-group-append">
<span class="input-group-text">.example.com</span>
</div>
</div>
</div>
</div>
Our second row:
我们的第二行:
So far, so good. Next, we’re going to place the Comments textarea, Photo file control and both checkboxes on the same row for medium and larger viewports:
到目前为止,一切都很好。 接下来,对于中等和较大的视口,我们将在同一行上放置“注释”文本区域,“照片”文件控件和两个复选框:
<div class="form-row"> <!-- #1 -->
<div class="form-group col-md-4"> <!-- #2 -->
<label for="comments">Comments (optional)</label>
<textarea class="form-control" id="comments" rows="3"></textarea>
</div>
<div class="form-group col-md-4"> <!-- #3 -->
<label for="photo">Your photo</label>
<input type="file" class="form-control-file" id="photo">
</div>
<div class="col-md-4"> <!-- #4 -->
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="userAgreement">
<label class="form-check-label" for="userAgreement">
I accept <a href="#">user agreement</a>
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="newsletter">
<label class="form-check-label" for="newsletter">
I'd like to receive newsletters
</label>
</div>
</div>
</div>
Note that we’ve wrapped both checkboxes in one column (#4) for a nice layout.
请注意,我们已经将两个复选框都包装在一个列中(#4),以获得一个不错的布局。
Lastly, let’s style the buttons. I think they can occupy a single column:
最后,让我们设计按钮的样式。 我认为他们可以只占据一列:
<div class="form-row mt-3">
<div class="col-xs-12"> <!-- #1 -->
<button type="submit" class="btn btn-outline-primary btn-lg">Register!</button>
<a href="#" class="btn btn-link">Back</a>
</div>
</div>
This is how our form looks now:
现在,我们的表单是这样的:
Here’s the final result on CodePen:
这是在CodePen上的最终结果:
See the Pen Sitepoint Bootstrap 4 Form With Rows by SitePoint (@SitePoint) on CodePen.
请参阅CodePen上的Pen Sitepoint Bootstrap 4表格 ,其中包含SitePoint( @SitePoint )的行 数 。
水平表格 (Horizontal Forms)
The grid system may also be leveraged to create horizontal forms — that is, forms that have the label and input elements on the same row. To achieve this result, the Bootstrap form component offers the col-form-label
class to be added to the labels.
网格系统也可以用于创建水平表单 ,即在同一行上具有标签和输入元素的表单。 为了获得此结果,Bootstrap表单组件提供了col-form-label
类,该类将添加到标签中。
Let’s create a small demo representing a horizontal form:
让我们创建一个代表水平形式的小演示:
<div class="container">
<p class="h1">Register</p>
<form class="mt-3">
<div class="form-group row"> <!-- #1 -->
<label for="email" class="col-sm-2 col-form-label">Email address</label> <!-- #2 -->
<div class="col-sm-10"> <!-- #3 -->
<input type="email" class="form-control"
id="email" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">
For authentication purposes only. We will never share your email with anyone!
</small>
</div>
</div>
<div class="form-group row">
<label for="password" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control"
id="password" placeholder="Password">
</div>
</div>
<div class="form-group row mt-3">
<div class="col-10 offset-2"> <!-- #4 -->
<button type="submit" class="btn btn-outline-primary">Register!</button>
<a href="#" class="btn btn-link">Back</a>
</div>
</div>
</form>
</div>
The main things to note here are:
这里要注意的主要事情是:
#1. Each form group is assigned a
row
class#1。 每个表单组被分配一个
row
类#2. Labels are assigned the
col-form-label
class#2。 标签被指定为
col-form-label
类#3. Inputs (and accompanying help blocks) are wrapped into separate
div
s#3。 输入(和随附的帮助块)包装在单独的
div
#4. For buttons we are additionally providing the
offset-2
class, so that they’re moved to the right and vertically aligned with the inputs.#4。 对于按钮,我们还提供了
offset-2
类,以便将它们移到右侧并与输入垂直对齐。
This is how the form looks:
表单外观如下:
What about the checkboxes? Well, we can also apply some offset and vertically align them with the buttons and inputs:
复选框呢? 好吧,我们还可以应用一些偏移并将它们与按钮和输入垂直对齐:
<div class="form-group row"> <!-- #1 -->
<div class="col-10 offset-2"> <!-- #2 -->
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="userAgreement">
<label class="form-check-label" for="userAgreement">
I accept <a href="#">user agreement</a>
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="newsletter">
<label class="form-check-label" for="newsletter">
I'd like to receive newsletters
</label>
</div>
</div>
</div>
And that’s our final version of the form:
这是表格的最终版本:
All elements have nice spacing so the UI is not visually cluttered. The source code for this example can also be found on CodePen.
所有元素都具有良好的间距,因此UI不会显得杂乱无章。 此示例的源代码也可以在CodePen上找到。
See the Pen Sitepoint Bootstrap 4 Horizontal Form by SitePoint (@SitePoint) on CodePen.
请参阅CodePen上的SitePoint ( @SitePoint )的Pen Sitepoint Bootstrap 4水平表格 。
内联表格 (Inline Forms)
Inline forms are also very common these days. Such forms may be employed to display search or sign in features. Let’s see them in action by creating a “Subscribe to newsletter” form:
如今, 内联表单也很常见。 这样的形式可以用于显示搜索或登录特征。 让我们通过创建“订阅新闻简报”表单来查看它们的作用:
<div class="container">
<p class="h1">Subscribe to our newsletter</p>
<form class="form-inline"> <!-- #1 -- >
<label class="sr-only" for="email">Name</label> <!-- #2 -- >
<input type="text" class="form-control mb-2 mr-sm-2 form-control-sm" id="email" placeholder="Email"> <!-- #3 -- >
<div class="form-check mb-2 mr-sm-2"> <!-- #4 -- >
<input class="form-check-input" type="checkbox" id="partners" value="1">
<label class="form-check-label" for="partners">
Receive news from our partners
</label>
</div>
<button type="submit" class="btn btn-primary mb-2 btn-sm">Subscribe</button> <!-- #5 -- >
</form>
</div>
The main things to note here are:
这里要注意的主要事情是:
#1. The form must be assigned a Bootstrap form component
form-inline
class. Note, however, that the form elements will appear inline only for viewports larger than 575px. For smaller screens, they’ll be stacked.#1。 必须为表单分配一个Bootstrap表单组件
form-inline
类。 但是请注意,仅当视口大于575px时,表单元素才会内联显示。 对于较小的屏幕,将它们堆叠在一起。- #2. We’re hiding the label and displaying it only for screen readers. #2。 我们将隐藏标签并仅将其显示给屏幕阅读器。
#3. The input has right margin for small and larger viewports with the help of the
mr-sm-2
class. We don’t require this margin for extra small screens because the elements will be stacked, as explained above. Apart from that, the input is made smaller with theform-control-sm
class.#3。 借助
mr-sm-2
类,对于较小和较大的视口,输入具有正确的边距。 如上所述,我们不需要为多余的小屏幕留出余量,因为元素将被堆叠在一起。 除此之外,form-control-sm
类使输入变小。- #4. The checkbox also has a right margin. #4。 复选框也有右边距。
#5. The button is made smaller as well using the
btn-sm
class.#5。 使用
btn-sm
类也可以使按钮变小。
Here’s the result:
结果如下:
The source code can also be found on CodePen:
也可以在CodePen上找到源代码:
See the Pen Sitepoint Bootstrap 4 Inline Form by SitePoint (@SitePoint) on CodePen.
请参阅CodePen上的SitePoint ( @SitePoint )提供的Pen Sitepoint Bootstrap 4内联表单 。
表格验证 (Form Validation)
Another very important thing is validation of users’ input. As a rule of thumb, we should never blindly trust the data submitted by users because they can make mistakes and provide incorrect values. This, in turn, might lead to the web application not working correctly, or worse. So we should always perform validations.
另一个非常重要的事情是验证用户输入。 根据经验,我们绝不能盲目信任用户提交的数据,因为它们可能会犯错误并提供不正确的值。 反过来,这可能会导致Web应用程序无法正常运行,甚至更糟。 因此,我们应该始终执行验证。
The first line of defense is client-side validation. Of course, we could rely on the browser’s predefined validation rules (for instance, modern browsers check the email’s format entered in the field with the corresponding type) but it’s not generally recommended by Bootstrap. Instead, we can make use of the Bootstrap form component’s custom validation styles.
第一道防线是客户端验证 。 当然,我们可以依靠浏览器的预定义验证规则(例如,现代的浏览器会使用相应的类型检查在字段中输入的电子邮件格式),但是Bootstrap通常不建议这样做。 相反,我们可以利用Bootstrap表单组件的自定义验证样式 。
To take advantage of these styles, we should disable the browser’s default validation mechanism by adding the novalidate
attribute to the form. Also, we should add a needs-validation
class:
要利用这些样式,我们应该通过向表单添加novalidate
属性来禁用浏览器的默认验证机制。 另外,我们应该添加一个needs-validation
类:
<div class="container">
<p class="h1">Register</p>
<form class="needs-validation" novalidate> <!-- #1 -->
</form>
</div>
Next, we simply display all the necessary fields as usual:
接下来,我们像往常一样简单地显示所有必要的字段:
<form class="needs-validation" novalidate>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email"
placeholder="Email" required> <!-- #1 -->
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password"
placeholder="Password" required minlength="6"> <!-- #2 -->
</div>
<div class="form-group mt-3">
<button class="btn btn-primary" type="submit">Register!</button>
</div>
</form>
Note that we’ve provided the require
attribute for both inputs (#1, #2) as well as minlength
for the password field (#2). This will make sure that users don’t send an empty form.
请注意,我们为两个输入(#1,#2)以及密码字段的minlength
(#2)都提供了require
属性。 这将确保用户不会发送空白表格。
What’s interesting is that each input may also contain two optional Bootstrap form component help blocks: valid-feedback
and invalid-feedback
. The first one is displayed when the data is correct, whereas the latter is shown only if users make a mistake. Let’s add these blocks now:
有趣的是,每个输入还可能包含两个可选的Bootstrap表单组件帮助块: valid-feedback
和invalid-feedback
。 当数据正确时显示第一个,而仅当用户输入错误时才显示后一个。 现在添加这些块:
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email"
placeholder="Email" required>
<div class="valid-feedback"> <!-- #1 -->
Looks good!
</div>
<div class="invalid-feedback"> <!-- #2 -->
The email is required!
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password"
placeholder="Password" required minlength="6">
<div class="valid-feedback">
Great!
</div>
<div class="invalid-feedback"> <!-- #3 -->
The password must contain at least 6 characters!
</div>
</div>
Lastly, we need some JavaScript to perform the actual validation and prevent the form from being submitted if an error is found:
最后,我们需要一些JavaScript来执行实际的验证,并在发现错误时阻止表单提交:
<!-- your form goes here... -->
<script>
(function() {
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation');
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>
Here, we grab all the forms that require validation and check if the entered data is correct. If it’s not, we prevent the submission process. Also, note that we must add a Bootstrap form component was-validated
class to the form. Each child field is also assigned either an :invalid
or :valid
pseudo class. These classes add a green or a red border around the input accordingly and display the proper feedback message.
在这里,我们获取所有需要验证的表格,并检查输入的数据是否正确。 如果不是这样,我们将阻止提交过程。 另外,请注意,我们必须向表单添加Bootstrap表单组件was-validated
类。 每个子字段也被分配了:invalid
或:valid
伪类。 这些类在输入周围相应地添加绿色或红色边框,并显示正确的反馈消息。
Here is the result:
结果如下:
On CodePen:
在CodePen上:
See the Pen Sitepoint Bootstrap 4 Form Validation by SitePoint (@SitePoint) on CodePen.
请参阅CodePen上的SitePoint ( @SitePoint )进行的Pen Sitepoint Bootstrap 4表单验证 。
This is how the style applied to the :valid
pseudo class looks in the browser’s developer tools:
这是应用于:valid
伪类的样式在浏览器的开发人员工具中的外观:
Lastly, note that the Bootstrap form component supports server-side validation as well. All we have to do is mark the inputs with either the is-valid
or is-invalid
classes. Feedback blocks also work fine with this type of validation.
最后,请注意,Bootstrap表单组件也支持服务器端验证 。 我们要做的就是用is-valid
或is-invalid
类标记输入。 反馈块也可以在这种类型的验证中正常工作。
结论 (Conclusion)
In this article, we’ve taken quite a long journey through the features of the Bootstrap form component and discussed various types of forms that come bundled with the latest release of Bootstrap. We’ve seen how to style various form elements, how to create forms based on the Bootstrap grid system, how to craft horizontal and inline forms. On top of that, we’ve discussed how the client-side validation rules can be implemented and how to style valid and invalid form inputs.
在本文中,我们花了很长的时间来了解Bootstrap表单组件的功能,并讨论了与最新版本的Bootstrap捆绑在一起的各种类型的表单 。 我们已经了解了如何设置各种表单元素的样式,如何基于Bootstrap网格系统创建表单,如何制作水平表单和嵌入式表单。 最重要的是,我们讨论了如何实现客户端验证规则以及如何设置有效和无效表单输入的样式。
I really hope that by now you’re ready to apply all this knowledge into practice and start building your own fancy forms!
我真的希望到现在为止您已经准备好将所有这些知识应用到实践中,并开始建立自己的幻想形式!
For more questions, don’t hesitate to use the comments section below.
如有其他疑问,请随时使用下面的评论部分。
If you’re building a site with Bootstrap that requires a login portal, check out our Creating a Login Portal with Bootstrap 4 course, which helps you get to grips with cards, forms, buttons and grids.
如果您要使用Bootstrap构建需要登录门户的网站,请查看我们的使用Bootstrap 4创建登录门户课程,该课程可帮助您掌握卡片,表单,按钮和网格。
翻译自: https://www.sitepoint.com/deep-dive-bootstrap-form-component/
bootstrap组件