【发布时间】:2021-05-31 20:56:47
【问题描述】:
我使用 Bootstrap 4 / JS 表单验证 (https://getbootstrap.com/docs/4.0/components/forms/#custom-styles),它按预期工作。
我尝试添加相同的格式和提交规则来比较两个密码字段,密码 ('#pw') 和重复密码 ('#pwRepeat'),以便显示匹配时为绿色单元格边框和复选标记图标,不匹配时为红色单元格边框和错误图标。
我的问题是我无法让它触发无效格式。当密码不匹配时手动将其设置为无效(对应的行见下面的 cmets)。
有人可以告诉我如何正确执行此操作并提供简短说明吗?
我的 JS:
(function() {
'use strict';
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
var pw = document.getElementById('pw').value; // $('#pw').val();
var pwRepeat = document.getElementById('pwRepeat').value; // $('#pwRepeat').val();
if(pwRepeat != pw) {
// set cell border color to red and show error icon for invalid input
pwRepeat.addClass('invalid'); // not working
}
if(form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
// submit if no errors where found
if((pwRepeat == pw) && (form.checkValidity() === true)) {
// do stuff
}
}, false);
});
},
false);
})();
非常感谢,
蒂姆
【问题讨论】:
-
请使用
<>工具创建完整的sn-p
标签: javascript forms twitter-bootstrap validation bootstrap-4