How to make select2 work with jquery.validation plugin?

Solution 1:

Just add ignore: [], in Your form validation function. It will enable hidden field validation.So You will get validation for Select 2

$("#ContactForm").validate({
  ignore: [],       
  rules: {
    //Rules
  },
  messages: {
    //messages
  }
});

Solution 2:

As a tip, please consider that the validate js bind itself to changes of select not select 2. This cause problem in below case:

  1. There is a required select box which is converted to select2
  2. You click the submit and the error shows that the select box is required.
  3. You select some option from select 2.
  4. The validation error does not hide automatically

You can fix it with:

     $("select").on("select2:close", function (e) {  
        $(this).valid(); 
    });

Solution 3:

In Addition to ABIRAMAN's answer here is some code that

  • Makes the select2 box red when errors appear
  • List the error below the select2 box

<style>
  span.error{
    outline: none;
    border: 1px solid #800000;
    box-shadow: 0 0 5px 1px #800000;
  }
</style>

<script>
 $("#form").validate({
     rules: {
       email: "required"
     },
     highlight: function (element, errorClass, validClass) {
       var elem = $(element);
       if (elem.hasClass("select2-hidden-accessible")) {
           $("#select2-" + elem.attr("id") + "-container").parent().addClass(errorClass); 
       } else {
           elem.addClass(errorClass);
       }
     },    
     unhighlight: function (element, errorClass, validClass) {
         var elem = $(element);
         if (elem.hasClass("select2-hidden-accessible")) {
              $("#select2-" + elem.attr("id") + "-container").parent().removeClass(errorClass);
         } else {
             elem.removeClass(errorClass);
         }
     },
     errorPlacement: function(error, element) {
       var elem = $(element);
       if (elem.hasClass("select2-hidden-accessible")) {
           element = $("#select2-" + elem.attr("id") + "-container").parent(); 
           error.insertAfter(element);
       } else {
           error.insertAfter(element);
       }
     }
   });

$('select').select2({}).on("change", function (e) {
  $(this).valid()
});
</script>