3

I have read I have read Bootstrap with jQuery Validation Plugin and it's helpful, but it's Bootstrap 3, not Bootstrap 4..

I'm using JQuery Validate with Bootstrap 4, but can't seem to get the label and input field to highlight red when it's invalid.

I thought the valid and invalid input classes were default in BS, link? Maybe i'm using them incorrectly.

My code is below, here's a fiddle.

HTML

<form id="myform">
  <div class="row">
    <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
      <div class="form-group">
        <label for="name" class="control-label">Email address</label>
        <input type="text" class="form-control" id="name" name="name" placeholder="Name" required>
      </div>
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

JQuery

$(function() {
  $("#myform").validate({
    rules: {
      name: {
        required: true,
        minlength: 2
      }
    },
    highlight: function(element) {
      $(element).closest('.form-group').removeClass('valid').addClass('invalid');
    },
    unhighlight: function(element) {
      $(element).closest('.form-group').removeClass('invalid').addClass('valid');
    },
  });
})

Any help is appreciated.

TheOrdinaryGeek
  • 2,273
  • 5
  • 21
  • 47

1 Answers1

5

These classes have changed in the most recent release. valid was renamed to is-valid and invalid is is-invalid.

Also, they need to be applied to inputs, not input group wrappers.

Edit:

You need to reorder the input and label if you want both to be highlighted.

$(function() {
  $("#myform").validate({
    rules: {
      name: {
        required: true,
        minlength: 2
      }
    },
    highlight: function(element) {
      $(element).removeClass('is-valid').addClass('is-invalid');
    },
    unhighlight: function(element) {
      $(element).removeClass('is-invalid').addClass('is-valid');
    },
  });
})
.reversed{padding: 3rem 0 0 0;}
.reversed .control-label{margin: -4.5rem 0 0 0; float: left;}

input.is-valid ~ label{color: green;}
input.is-invalid ~ label{color: red;}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>

<form id="myform">
  <div class="row">
    <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
      <div class="form-group reversed"><!-- added reversed class -->
        <input type="text" class="form-control" id="name" name="name" placeholder="Name" required>
        <label for="name" class="control-label">Email address</label>
      </div>
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>
Serg Chernata
  • 12,280
  • 6
  • 32
  • 50