Yet another jQuery validation post: make it work with bootstrap

Yet another jQuery validation post: make it work with bootstrap

I recently needed to enforce rules on a form that I laid out with bootstrap. The form looked great but required a selection of values or it wouldn’t yield correct results. If designed well, a form won’t need a lengthy explanation how to make it work. I opted to use jQuery validation so I could focus on the user experience first and code details second. The jQuery validation library adds value in this scenario because it is well tested so I don’t have to spend time re-inventing code to do this work.  If the required fields are obvious when someone uses the form then there is less frustration.

Here is the html:

<form id="form_to_validate" novalidate="novalidate" method="post">
  <div class="col-sm-12">
    <div class="form-group" id="divisionlist">
      <select id="divisions" name="divisions" class="form-control" required="required" multiple="" size="5">
        <option value="1">01 - Division 1</option>
        <option value="2">02 - Division 2</option>
        <option value="3">03 - Division 3</option>
        <option value="4">04 - Division 4</option>
        <option value="5">05 - Division 5</option>
      </select>
    </div>
  </div>
</form>
<br/>
<button id="Validate">Validate!</button>
<span id="valid_result"></span>

Here is the Javascript:

$(function() {
  // override jquery validate plugin defaults to work with twitter bootstrap
  $.validator.setDefaults({
    highlight: function(element) {
      $(element).closest('.form-group').addClass('has-error');
    },
    unhighlight: function(element) {
      $(element).closest('.form-group').removeClass('has-error');
    },
    errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function(error, element) {
      if (element.parent('.input-group').length) {
        error.insertAfter(element.parent());
      } else {
        error.insertAfter(element);
      }
    }
  });

  //set up the validation rules
  $('#form_to_validate').validate({
    rules: {
      divisions: 'required',
    },
    errorElement: 'div',
  });

  //this bit uses button to tests that the validation is working
  //it's not part of the published solution.
  $('#Validate').click(function() {
    var valid_form = $('#form_to_validate').valid();
    if (valid_form) {
      $("#valid_result").text("valid!");
    } else {
      $("#valid_result").text("NOT valid!");
    }
    return false;
  });
});

Here is the end result when not valid:

form_not_validHere is the end result when valid:

form_is_validIt’s important to not that I had to include 4 libraries on this page to get this to work. These libraries are what do all the difficult work. I’m just using them to get easy validation with a good looking result.

Bootstrap 3.3.6 css

Bootstrap 3.3.6 js min

jQuery Validate 1.14.0

jQuery 2.2.2 js min

So let’s work through what’s going on here. In the code I pasted above there are two parts that do all the magic. First, this snippet shows the jQuery validation library how to work with bootstraps css rules. Specifically, it tells the library which elements in a form-group should be decorated with the ‘has-error’ css rule that turns elements red when a rule is violated.

$(function() {
  // override jquery validate plugin defaults to work with twitter bootstrap
  $.validator.setDefaults({
    highlight: function(element) {
      $(element).closest('.form-group').addClass('has-error');
    },
    unhighlight: function(element) {
      $(element).closest('.form-group').removeClass('has-error');
    },
    errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function(error, element) {
      if (element.parent('.input-group').length) {
        error.insertAfter(element.parent());
      } else {
        error.insertAfter(element);
      }
    }
  });

Second, this bit tells the jQuery validate framework which fields to perform it’s validation.

  //set up the validation rules
  $('#form_to_validate').validate({
    rules: {
      divisions: 'required',
    },
    errorElement: 'div',
  });

With around 25 very short lines of JavaScript you can enable good looking validation on a nicely laid out form.

A link to JSFiddle with a complete working solution.

Happy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *