【发布时间】:2018-12-27 04:12:50
【问题描述】:
我尝试使用引导程序验证空字段的表单。 使用 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);
});
})();
【问题讨论】:
-
它似乎工作正常。
-
非必填字段变为绿色。我希望他们没有经过验证,保持原样
-
您找到解决方案了吗?有同样的问题....
标签: javascript html bootstrap-4