我尝试使用引导程序验证空字段的表单。 使用form.checkValidity()方法提交和验证时,必填字段的样式正确。 有些字段没有必填属性,但其样式设置为正确。 为什么这些不需要的字段进行有效性检查?引导程序是正常行为还是出问题了?
这是我从文档中修改的代码:https://jsfiddle.net/ksilix/v01w3a4h/43/
HTML:
<form id="form1" novalidate>
<div class="form-group">
<label for="validationCustom01">Name</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="name required" required>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
Required!
</div>
</div>
<div class="form-group">
<label for="validationCustom02">Optional</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="Optional">
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
Required!
</div>
</div>
<label for="radio-group1">Optional radio checked</label>
<div class="form-group" id="radio-group1">
<div class="form-check">
<input class="form-check-input" type="radio" value="1" id="radio1" name="radios1" checked>
<label class="form-check-label" for="radio1">
Opt1
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" value="2" id="radio2" name="radios1">
<label class="form-check-label" for="radio2">
Opt2
</label>
</div>
</div>
<label for="radio-group2">Optional radio not checked</label>
<div class="form-group" id="radio-group2">
<div class="form-check">
<input class="form-check-input" type="radio" value="1" id="radio3" name="radios2">
<label class="form-check-label" for="radio3">
Opt3
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" value="2" id="radio4" name="radios2">
<label class="form-check-label" for="radio4">
Opt4
</label>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
Javascript:
// 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 form = document.getElementById('form1');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
})();
答案 0 :(得分:1)
根据文档,任何与验证不符的字段都将具有:valid
CSS伪类,其结果将触发Bootstrap表单样式。
.was-validated .form-check-input:valid~.form-check-label {...
Bootstrap建议使用自己的自定义验证样式! Bootstrap Form Validation Doc