(函数(){'使用严格'//获取我们想要应用自定义 Bootstrap 验证样式的所有表单var forms = document.querySelectorAll('.needs-validation')//遍历它们并防止提交Array.prototype.slice.call(表单).forEach(函数(形式){form.addEventListener('submit', function (event) {如果(!form.checkValidity()){event.preventDefault()event.stopPropagation()}form.classList.add('已验证')}, 错误的)})})()
I'm trying to implement validation by Bootstrap and I've pasted the following sample on my page:
<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>
I can see that the appearance of the input control has changed (it's a bit rounded and much more aesthetic now) but it still doesn't show the green border as can be seen on the page linked to. The Bootstrap I'm linking to is pointed out as follows.
Since jQuery is no longer required for Bootstrap 5, it's easy to do client-side validation with vanilla JavaScript. The docs include a generic code example that should work on all forms with 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)
})
})()
The valid state selectors use the was-validated class which would be added dynamically after validating the form via client-side JavaScript. For example...