Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip validation feedback on certain Bootstrap 4 inputs

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

like image 461
Daniel Olivares Avatar asked Jan 18 '18 02:01

Daniel Olivares


2 Answers

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

like image 126
ksiger Avatar answered Oct 24 '22 02:10

ksiger


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;
}
like image 23
Rafael Avatar answered Oct 24 '22 03:10

Rafael