如何将 Bootstrap 4 验证设计添加到 select2

How to add Bootstrap 4 validation design into select2

我们需要根据Bootstrap 4 default javascript validation API设计select2启用字段。我们尝试将必要的 类 分配给 select2 containerCssClass,如下所示:

let forms = document.getElementsByClassName('needs-validation');
Array.prototype.filter.call(forms, function (form) {
    form.addEventListener('submit', function (event) {
        $('.form-control.select2:invalid').select2({
            containerCssClass: 'form-control is-invalid border-danger'
        });
        $('.form-control.select2:valid').select2({
            containerCssClass: 'form-control is-valid border-success'
        });
    }, false);
});

但它总是显示无效的样式,即使该字段填充了有效数据。我们如何解决这个问题?

使用CSS你可以很容易地解决这个问题。在这里你可以得到 SCSS/LESS 代码:

.was-validated {
    .form-control.select2 + .select2-container .select2-selection,
    .custom-select.select2 + .select2-container .select2-selection {
        padding-right: calc(1.6em + 0.75rem);
        background-repeat: no-repeat;
        background-position: center right calc(0.4em + 0.1875rem);
        background-size: calc(0.8em + 0.375rem) calc(0.8em + 0.375rem);
    }

    .form-control.select2:invalid + .select2-container .select2-selection,
    .custom-select.select2:invalid + .select2-container .select2-selection {
        border-color: #e3342f;
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23e3342f' viewBox='-2 -2 7 7'%3e%3cpath stroke='%23e3342f' d='M0 0l3 3m0-3L0 3'/%3e%3ccircle r='.5'/%3e%3ccircle cx='3' r='.5'/%3e%3ccircle cy='3' r='.5'/%3e%3ccircle cx='3' cy='3' r='.5'/%3e%3c/svg%3E");
    }

    .form-control.select2:valid + .select2-container .select2-selection,
    .custom-select.select2:valid + .select2-container .select2-selection {
        border-color: #38c172;
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%2338c172' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
    }
}

Bootstrap 4.3.1 中提到的默认验证 API 在提交表单时添加了一个 class (.was-validated) 并且他们做了一些:valid:invalid 状态的样式。我们只是简单地复制了这些样式并 DOM 遍历以将它们应用到 Select2 容器。

这样当表单字段状态改变时样式也会改变。