CSS 强制在 Bootstrap 4 中显示无效反馈

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50431450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 11:11:34  来源:igfitidea点击:

Force to show invalid-feedback in Bootstrap 4

csstwitter-bootstrapbootstrap-4

提问by KimchiMan

Let's say I have HTML like this:

假设我有这样的 HTML:

...
<div class="form-group">
    <div class="form-check">
        <input class="form-check-input" type="checkbox" id="invalidCheck">
        <label class="form-check-label" for="invalidCheck">
            Agree to something
        </label>
    </div>

    <div class="invalid-feedback">
        I am outside of `form-check`!
    </div>
</div>
...

I want to forceto show the <div class="invalid-feedback">...without using JavaScript (want to use Bootstrap CSS only). And I know I can use CSS classes like was-validatedor is-invalid, but invalid-feedbackis outside of form-check. Is there an easy and simple way to show invalid-feedbackby adding Bootstrap related CSS classes?

我想强制显示<div class="invalid-feedback">...而不使用 JavaScript(只想使用 Bootstrap CSS)。而且我知道我可以使用像was-validated或 之类的 CSS 类is-invalid,但invalid-feedback不在form-check. invalid-feedback通过添加与 Bootstrap 相关的 CSS 类,是否有一种简单而简单的方式来显示?

I found one solution:

我找到了一个解决方案:

<div class="invalid-feedback d-block">
    Now I am visible!
</div>

But I feel like it's a hacky solution. Please advise!

但我觉得这是一个hacky解决方案。请指教!

回答by Yevgeniy Afanasyev

Use display classes to display it manually for example d-block

例如,使用显示类手动显示它 d-block

use it like so

像这样使用它

<div class="valid-feedback d-block"> 

or

或者

<div class="invalid-feedback d-block">

Find more in documentation

在文档中查找更多信息

回答by Yevgeniy Afanasyev

There are better ways.

有更好的方法。

1)Look into a was-validatedclass, that you can set on the form like so

1)查看一个was-validated类,您可以像这样在表单上设置

<form action="..." class="was-validated" method="POST" novalidate>

When set on the form it displays validation feedback and also colorcodes the input field.

在表单上设置时,它会显示验证反馈并对输入字段进行颜色编码。

Just add it conditionally on your form, when validation failed on the server side.

服务器端验证失败时,只需在您的表单上有条件地添加它。

2)Or you can use some JavaScriptto be in control of what is displayed. You can add this class dynamically

2)或者您可以使用一些JavaScript来控制显示的内容。您可以动态添加此类

$('form').addClass('was-validated');

and you can also dynamically check if the form is valid like so

并且您还可以像这样动态检查表单是否有效

 if ($('form').checkValidity()) {...