By following Bootstrap's docs on form validation, I can validate my forms, but I haven't found a way so that specific fields (e.g. a text input or a checkbox) don't show validation feedback while all of the others do.
What I mean is: how can I make that some specific fields either skip getting the :valid
or :invalid
pseudoclasses when the form is validated, or even if they do get the pseudoclasses applied to them, how can I skip them from being visually formatted as the other fields?
Maybe there is a class that acts as the opposite of .was-validated
that can be applied to specific fields?
Bootstrap version: v4.0.0-beta.3
Not required form fields has a pseudoclass :valid
. So if you add class .was-validated
to your form, all of them will be highlighted as valid.
To highlight only requered fields you should not use default validation but check only neccessary fields like this:
if ($(this).val() != "" && $(this).prop("validity").valid) {
$(this).addClass("is-valid");
} else {
$(this).addClass("is-invalid");
}
If you use bootstrap4, it will highlight these fields properly after code is executed.
You can examine it on JSFiddle
Because not required fields are valid by default
You can make an override :valid
pseudo class by adding to input .form-control
a class ex.: no-validate
If you are using npm and you are importing boostrap you can use bootstrap variables
.form-control.no-validate:valid {
border-color: $input-border-color;
padding: $input-padding-x;
background: $input-bg;
}
If not, you can just add default values:
.form-control.no-validate:valid {
border-color: #ced4da;
padding-right: .75rem;
background: none;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With