Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force to show invalid-feedback in Bootstrap 4

Let's say I have HTML like this:

...
<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 force to 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-validated or is-invalid, but invalid-feedback is outside of form-check. Is there an easy and simple way to show invalid-feedback by adding Bootstrap related CSS classes?

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!

like image 356
KimchiMan Avatar asked May 20 '18 03:05

KimchiMan


People also ask

How can we make input field mandatory in bootstrap?

1. Required attribute: If you want to make an input mandatory to be entered by the user, you can use the required attribute. This attribute can be used with any input type such as email, URL, text, file, password, checkbox, radio, etc. This can help to make any input field mandatory.

Which class does bootstrap 4 provide in order to be used only when the form control is invalid?

Here's how form validation works with Bootstrap: HTML form validation is applied via CSS's two pseudo-classes, :invalid and :valid . It applies to <input> , <select> , and <textarea> elements. Bootstrap scopes the :invalid and :valid styles to parent .was-validated class, usually applied to the <form> .

How do I show a field required in bootstrap?

This is pretty useful in giving a visual indication to the user when a form field is required. There will now be a nice little “*” after the label for “Required Field”.


1 Answers

There are better ways.

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

<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 JavaScript to be in control of what is displayed. You can add this class dynamically

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

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

 if ($('form').checkValidity()) {...
like image 121
Yevgeniy Afanasyev Avatar answered Oct 23 '22 03:10

Yevgeniy Afanasyev