引导程序 5(2021 年更新)
由于 Bootstrap 5 不再需要 jQuery,因此很容易使用 vanilla JavaScript 进行客户端验证。文档包含一个通用代码示例,该示例适用于所有带有needs-validation
..
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
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)
})
})()
Bootstrap 5 表单验证演示
Bootstrap 4(原始答案)
自 Bootstrap 4 beta 版本起,验证已更改。
有效状态选择器使用在was-validated
通过客户端JavaScript 验证表单后动态添加的类。例如...
<form class="container was-validated" novalidate="">
<div class="form-group">
<label class="form-control-label" for="inputSuccess1">Input with success</label>
<input type="text" class="form-control" name="i1" id="inputSuccess1">
<div class="valid-feedback">Success! You've done it.</div>
</div>
<div class="form-group">
<label class="form-control-label" for="inputSuccess2">Input with danger</label>
<input type="text" class="form-control" name="i2" required="" id="inputSuccess2">
<div class="invalid-feedback">That didn't work.</div>
</div>
<div class="">
<button type="submit" class="btn btn-secondary">Text</button>
</div>
</form>
https://codeply.com/go/45rU7UOhFo
表单验证示例演示 - Bootstrap 4.0.0
如文档中所述,如果您打算使用服务器端验证,您可以简单地在表单控件上设置is-valid
或类...is-invalid
<form class="container">
<div class="form-group">
<label class="form-control-label" for="inputSuccess1">Input with success</label>
<input type="text" class="form-control is-valid" id="inputSuccess1">
<div class="valid-feedback">Success! You've done it.</div>
</div>
</form>