【问题标题】:Bootstrap 4 form validation: Add same rule for password comparisonBootstrap 4 表单验证:为密码比较添加相同的规则
【发布时间】: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


【解决方案1】:

这里有几个问题。

var pwRepeat = document.getElementById('pwRepeat').value;

pwRepeat 是一个值而不是一个元素,因此以下内容将不起作用,并且 addClass 也不正确。

pwRepeat.addClass('invalid'); 

将以上内容替换为:

 document.getElementById('pwRepeat').classList.add("invalid");

鉴于没有有效的示例,上述内容未经测试,但应该为您指明正确的方向,了解为什么目前这不起作用。

【讨论】:

  • 非常感谢。我在这里混合了 JS 和 jQuery,打字速度太快了。我将尝试创建一个工作示例来找出为什么仍未设置颜色。
  • 可能 .invalid css 边框颜色不会覆盖现有的边框颜色。尝试添加 !important 。像 .invalid { border : solid 1px red !important;} 做不到这一点,发布 CSS 和 HTML。
  • 谢谢。我意识到所需的默认类称为 is-invalid / is-valid 而不是无效/有效。更改此项似乎适用于边框和图标。
猜你喜欢
  • 1970-01-01
  • 2014-05-12
  • 2015-08-30
  • 1970-01-01
  • 2015-10-10
  • 2018-02-10
  • 1970-01-01
  • 2011-10-29
  • 2019-04-11
相关资源
最近更新 更多