Search code examples
htmlcssbootstrap-5

Apply Bootstrap custom validation only to invalid fields


I am learning about Bootstrap, and I was wondering if there is a simple way of changing the style of a field only when it is invalid?

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<div class="container">
  <form class="needs-validation was-validated" novalidate>
    <label for="sample" class="form-label">Number</label>
    <input type="number" class="form-control" id="sample" min="1" step="1" required />
  </form>
</div>

This is the code I am playing around with. I can get the input field green/red for valid/invalid. I only want it to be red when it is invalid, and remain gray (and not have the green check mark) when it is valid.


Solution

  • By targeting the correct classes in CSS you can revert the changes from bootstrap :

    .container .form-control.is-valid, .container .was-validated .form-control:valid {
        border-color: initial;
        background-image: none;
        padding-inline-end: 12px;
    }
    
    .container .form-control.is-valid:focus, .container .was-validated .form-control:valid:focus {
       border-color: initial;
       box-shadow: initial;
    }
    

    With this, only the red/invalid will remain.

    Demo:

    .container .form-control.is-valid, .container .was-validated .form-control:valid {
        border-color: initial;
        background-image: none;
        padding-inline-end: 12px;
    }
    
    .container .form-control.is-valid:focus, .container .was-validated .form-control:valid:focus {
       border-color: initial;
       box-shadow: initial;
    }
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <div class="container">
      <form class="needs-validation was-validated" novalidate>
        <label for="sample" class="form-label">Number</label>
        <input type="number" class="form-control" id="sample" min="1" step="1" required />
      </form>
    </div>