Bootstrap 简明教程
Bootstrap - Validation
本章将讨论 Bootstrap 验证。Bootstrap 5 验证通过为用户提供有用的反馈、支持默认浏览器行为、自定义样式和 JavaScript 来增强 HTML5 表单验证。
How form validation works in Bootstrap
-
CSS 中的两个伪类 :invalid 和 :valid 用于提供 HTML 表单验证。它适用于 <textarea> 、 <select> 和 <input> 元素。
-
Bootstrap 应用 * :invalid* 和 :valid 样式到父 .was-validated 类。没有值的字段在页面加载时显示为无效。你选择何时激活它们(通常在表单提交后)。
-
要使用 Ajax 在动态提交后还原表单的原始外观,应从 <form> 中删除 .was-validated ,以重置其外观。
-
可以将伪类替换为 server-side validation 的 .is-invalid 和 .is-valid 类作为后备,而无需 .was-validated 父类。
-
目前,CSS 限制阻止我们直接对 DOM 中表单控件之前的 <label> 元素应用样式,而无需使用自定义 JavaScript。
-
由用于验证表单控件的不同 JavaScript 方法组成的 constraint validation API 受所有当代网络浏览器支持。
-
使用 browser default 样式或使用 HTML / CSS 创建自定义反馈样式。
-
在 JavaScript 中使用 setCustomValidity 方法进行独特的有效性消息。
我们来看看一些自定义表单验证样式、可选的服务端类和浏览器默认设置的示例。
Custom styles
-
向 <form> 中添加 novalidate 布尔属性,以接收来自 Bootstrap 的自定义验证消息。
-
以上布尔属性禁用浏览器默认的反馈工具提示,但 JavaScript 验证 API 仍可正常工作。提交此表单将触发 JavaScript 提供反馈,在表单控件上显示 :invalid 和 :valid 样式。
-
自定义反馈样式通过添加颜色、边框、焦点样式和背景图标来改善反馈沟通。 <select> 的背景图标仅适用于 .form-select ,而不适用于 .form-control 。
该示例演示带表单验证功能的 Bootstrap 表单,以确保在提交表单之前正确填写必填字段。
Example
您可以使用*编辑和运行*选项编辑并尝试运行此代码。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap - Validation</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form class="row g-3 needs-validation" novalidate>
<div class="col-md-4">
<label for="validationCustomName" class="form-label">Full Name</label>
<input type="text" class="form-control" id="validationCustomName" value="Jhon Miller" required>
<div class="invalid-feedback">
Correct input!
</div>
</div>
<div class="col-md-4">
<label for="validationCustomEmail" class="form-label">Email Id</label>
<div class="input-group has-validation">
<input type="text" class="form-control" id="validationCustomEmail" aria-describedby="inputGroupPrepend" required>
<span class="input-group-text" id="inputGroupPrepend">@tutorialspoint.com</span>
<div class="invalid-feedback">
Please enter correct mail id.
</div>
</div>
</div>
<div class="col-md-4">
<label for="validationCustomPhone" class="form-label">Mobile no</label>
<input type="text" class="form-control" id="validationCustomPhone" required>
<div class="invalid-feedback">
please enter correct mobile no.
</div>
</div>
<div class="col-md-6">
<label for="validationAddress" class="form-label">Address</label>
<input type="text" class="form-control" id="validationAddress" value="XYZ - 123" required>
<div class="valid-feedback">
Correct input!
</div>
</div>
</div>
<div class="col-md-3">
<label for="validationCustom" class="form-label">Gender</label>
<select class="form-select" id="validationCustom" required>
<option selected disabled value="">Choose...</option>
<option>Male</option>
<option>Female</option>
<option>Others</option>
</select>
<div class="invalid-feedback">
Please select gender.
</div>
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
I have reviewed and agree to Terms of Services and Privacy Policy.
</label>
<div class="invalid-feedback">
You must agree before submitting.
</div>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
<script>
(() => {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
const forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
</script>
</body>
</html>
以下 JavaScript 代码片段在有无效字段时禁用表单提交。它通过在表单中添加事件侦听器,以及如果表单无效则阻止默认表单提交行为,以实现此目的。
// Example JavaScript starter for disabling form submissions if there are invalid fields
(() => {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
const forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
Browser defaults
-
我们可以使用浏览器默认消息,而不是自定义验证消息。取决于您的浏览器和操作系统,反馈样式会略有不同。
-
虽然 CSS 无法用于设置这些反馈样式,但仍然可以使用 JavaScript 来更改反馈文本。
尝试提交以下示例中的表单,以了解默认浏览器验证消息是如何显示的。
Example
您可以使用*编辑和运行*选项编辑并尝试运行此代码。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Form - Validation</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form class="row g-3">
<div class="col-md-4">
<label for="validationDefaultName" class="form-label">Full Name</label>
<input type="text" class="form-control" id="validationDefaultName" value="name" required>
</div>
<div class="col-md-4">
<label for="validationDefaultEmail" class="form-label">Email Id</label>
<div class="input-group">
<input type="text" class="form-control" id="validationDefaultEmail" aria-describedby="inputGroupPrepend" required>
<span class="input-group-text" id="inputGroupPrepend">@tutorialspoint.com</span>
</div>
</div>
<div class="col-md-4">
<label for="validationDefaultMob" class="form-label">Mobile No</label>
<input type="text" class="form-control" id="validationDefaultMob" value="" required>
</div>
<div class="col-md-6">
<label for="validationDefaultAddress" class="form-label">Address</label>
<input type="text" class="form-control" id="validationDefaultAddress" required>
</div>
<div class="col-md-3">
<label for="validationDefaultGender" class="form-label">Gender</label>
<select class="form-select" id="validationDefaultGender" required>
<option selected disabled value="">Choose...</option>
<option>Male</option>
<option>Female</option>
<option>Others</option>
</select>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck2" required>
<label class="form-check-label" for="invalidCheck2">
I have reviewed and agree to Terms of Services and Privacy Policy.
</label>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
</body>
</html>
Server-side
-
建议进行客户端验证,但在进行服务器端验证的情况下,使用 .is-invalid 和 .is-valid 指令来表示表单字段状态。此外还考虑对这些类使用 .invalid-feedback 。
-
在字段无效的情况下,使用 aria-describedby 属性将无效反馈/错误消息链接至表单字段。(如果字段连接到了其他表单文本,允许引用多个 id。)
-
输入组需要一个附加的 .has-validation 类来处理 issues with border radius 。
Example
您可以使用*编辑和运行*选项编辑并尝试运行此代码。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap - Validation</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form class="row g-3">
<div class="col-md-4">
<label for="validationServerName" class="form-label">Full name</label>
<input type="text" class="form-control is-valid" id="validationServerName" value="Mark" required>
<div class="valid-feedback">
enter your name
</div>
</div>
<div class="col-md-4">
<label for="validationServerEmail" class="form-label">Email Id</label>
<div class="input-group has-validation">
<input type="text" class="form-control is-invalid" id="validationServerEmail"
aria-describedby="inputGroupPrepend3 validationServerEmailFeedback" required>
<span class="input-group-text" id="inputGroupPrepend3">@tutorialspoint.com</span>
<div id="validationServerEmailFeedback" class="invalid-feedback">
Please enter mail id.
</div>
</div>
</div>
<div class="col-md-4">
<label for="validationServerMob" class="form-label">Mobile no</label>
<input type="text" class="form-control is-valid" id="validationServerMob" value="" required>
<div class="valid-feedback">
Please enter mobile no
</div>
</div>
<div class="col-md-6">
<label for="validationServerAddress" class="form-label">Address</label>
<input type="text" class="form-control is-invalid" id="validationServerAddress"
aria-describedby="validationServerAddressFeedback" required>
<div id="validationServerAddressFeedback" class="invalid-feedback">
Please enter a valid Address.
</div>
</div>
<div class="col-md-3">
<label for="validationServer04" class="form-label">Gender</label>
<select class="form-select is-invalid" id="validationServer04" aria-describedby="validationServer04Feedback"
required>
<option selected disabled value="">Choose...</option>
<option>Male</option>
<option>Female</option>
<option>Others</option>
</select>
<div id="validationServer04Feedback" class="invalid-feedback">
Please select a valid gender.
</div>
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input is-invalid" type="checkbox" value="" id="invalidCheckPolicy"
aria-describedby="invalidCheckFeedback" required>
<label class="form-check-label" for="invalidCheckPolicy">
I have reviewed and agree to Terms of Services and Privacy Policy.
</label>
<div id="invalidCheckFeedback" class="invalid-feedback">
You must agree before submitting.
</div>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
</body>
</html>;
Supported elements
以下表单控件和组件支持验证样式:
-
<textarea> 和 <input> 使用 .form-control (允许输入组最多包含一个 .form-control )。
-
<select> using .form-select
-
.form-check
Example
您可以使用*编辑和运行*选项编辑并尝试运行此代码。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Form - Validation</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form class="was-validated">
<div class="mb-3">
<label for="validationTextarea" class="form-label">Add comment</label>
<textarea class="form-control" id="validationTextarea" placeholder="Comment Here" required></textarea>
<div class="invalid-feedback">
Add comment
</div>
</div>
<div class="form-check mb-3">
<input type="checkbox" class="form-check-input" id="validationFormCheck" required>
<label class="form-check-label" for="validationFormCheck">Item One</label>
<div class="invalid-feedback">Invalid Answer</div>
</div>
<div class="form-check">
<input type="radio" class="form-check-input" id="validationFormRadio1" name="radio-stacked" required>
<label class="form-check-label" for="validationFormRadio1">Item Two</label>
</div>
<div class="form-check mb-3">
<input type="radio" class="form-check-input" id="validationFormRadio2" name="radio-stacked" required>
<label class="form-check-label" for="validationFormRadio2">Item Three</label>
<div class="invalid-feedback">Invalid Answer</div>
</div>
<div class="mb-3">
<select class="form-select" required aria-label="select example">
<option value="">Gender</option>
<option value="1">Male</option>
<option value="2">Female</option>
<option value="3">Others</option>
</select>
<div class="invalid-feedback">Invalid selection</div>
</div>
<div class="mb-3">
<input type="file" class="form-control" aria-label="file example" required>
<div class="invalid-feedback">File size more than 256kb</div>
</div>
<div class="mb-3">
<button class="btn btn-primary" type="submit" disabled>Submit</button>
</div>
</form>
</body>
</html>
Tooltips
-
要以样式工具提示框显示验证反馈,则如果布局允许,将 .{valid|invalid}-feedback 类换成 .{valid|invalid}-tooltip 类。
-
要放置工具提示框,确保父级具备 position: relative 属性。
Example
您可以使用*编辑和运行*选项编辑并尝试运行此代码。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap - Validation</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form class="row g-3 needs-validation" novalidate>
<div class="col-md-4 position-relative">
<label for="validationTooltipName" class="form-label">Full Name</label>
<input type="text" class="form-control" id="validationTooltipName" value="Jhon Miller" required>
<div class="valid-tooltip">
Correct Input!
</div>
</div>
<div class="col-md-4 position-relative">
<label for="validationTooltipEmail" class="form-label">Email Id</label>
<div class="input-group has-validation">
<input type="text" class="form-control" id="validationTooltipEmail" aria-describedby="validationTooltipEmailPrepend" required>
<span class="input-group-text" id="validationTooltipEmailPrepend">@tutorialspoint.com</span>
<div class="invalid-tooltip">
Please enter mail id.
</div>
</div>
</div>
<div class="col-md-4 position-relative">
<label for="validationTooltipMob" class="form-label">Mobile no</label>
<input type="text" class="form-control" id="validationTooltipMob" required>
<div class="invalid-tooltip">
Please enter mobile no.
</div>
</div>
<div class="col-md-6 position-relative">
<label for="validationTooltipAddress" class="form-label">Address</label>
<input type="text" class="form-control" id="validationTooltipAddress" value="XYZ - 123" required>
<div class="valid-tooltip">
Correct Input!
</div>
</div>
<div class="col-md-3 position-relative">
<label for="validationTooltip04" class="form-label">Gender</label>
<select class="form-select" id="validationTooltip04" required>
<option selected disabled value="">Choose...</option>
<option>Male</option>
<option>Female</option>
<option>Others</option>
</select>
<div class="invalid-tooltip">
Please select a valid gender.
</div>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
<script>
(() => {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
const forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
</script>
</body>
</html>