How to make select2 work with jquery.validation plugin?

87,844

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>

Solution 4

I have detailed this in a blog post: http://chadkuehn.com/jquery-validate-select2/

When you place a Select2 on a SELECT tag it hides the original element. So in the validation plugin you must adjust the proper wrapping markup when highlighting and unhighlighting.

    highlight: function (element, errorClass, validClass) {
        var elem = $(element);
        if (elem.hasClass("select2-offscreen")) {
            $("#s2id_" + elem.attr("id") + " ul").addClass(errorClass);
        } else {
            elem.addClass(errorClass);
        }
    },

    unhighlight: function (element, errorClass, validClass) {
        var elem = $(element);
        if (elem.hasClass("select2-offscreen")) {
            $("#s2id_" + elem.attr("id") + " ul").removeClass(errorClass);
        } else {
            elem.removeClass(errorClass);
        }
    }

View a DEMO here.

Solution 5

Found an answer on the forums @ https://github.com/select2/select2/issues/215 posted by corinnaerin. Worked perfectly for me. Sample code at http://plnkr.co/edit/4QaSguIiYsJtLpuPF8Rc?p=preview

      var $select = $('select').select2({
        placeholder: 'Choose',
        allowClear: true
      });

      /*
       * When you change the value the select via select2, it triggers
       * a 'change' event, but the jquery validation plugin
       * only re-validates on 'blur'
       */
      $select.on('change', function() {
        $(this).trigger('blur');
      });

      $('#myForm').validate({
        ignore: 'input[type=hidden], .select2-input, .select2-focusser'
      });
Share:
87,844

Related videos on Youtube

user2323711
Author by

user2323711

Updated on October 18, 2020

Comments

  • user2323711
    user2323711 over 3 years

    I'm trying to validate select2 field using jquey.validation plugin but nothing happens.

    I want to make select required field.

    I'm using this custom validation function:

    $.validator.addMethod("requiredcountry", function(value, element, arg){
                  return arg != value;
             }, "Value must not equal arg.");
    

    and this is the rule:

    rules:
    {
     country:
     {
             required: true,
             requiredcountry: ""
     }
    }
    

    What select2 field should I use for the rule to match?

    I appreciate any idea how to make select2 working together with jquery.validation

    10x

  • Ken
    Ken about 9 years
    My current strategy has been to assign the ignore property to a class named "ignore-validation" like so: ignore: '.ignore-validation' Doing it this way enables you to turn validation on and off for a particular element at will simply by adding/removing that class name on the input element.
  • Ferry Meidianto
    Ferry Meidianto over 8 years
    $("select").on("select2-close", function (e) { $(this).valid(); });
  • Tsukasa
    Tsukasa about 8 years
    any chance of an update for select2 4.0.x. Doesn't seem to work.
  • SolaceBeforeDawn
    SolaceBeforeDawn over 7 years
    That is so simple - yet couldn't find any mention in the docs for Select2
  • e_i_pi
    e_i_pi about 7 years
    Fantastic, fixed my problem after a long time trying myself! +1
  • Ahmad Mobaraki
    Ahmad Mobaraki almost 7 years
    up vote for : $select.on('change', function() { $(this).trigger('blur'); });
  • Adam
    Adam over 6 years
    @Tsukasa you find an update in my answer stackoverflow.com/a/46953372/2311074
  • Nirav Thakar
    Nirav Thakar over 6 years
    It's my pleasure Damith
  • dearsina
    dearsina over 6 years
    If I'm not mistaken, "unhighlight" has been replaced by "success" in the newest version of the jQuery Validate script. I also had to change the if statement in the "unhighlight" section to the following: if (elem.parent().hasClass("select2")) { Because the select2-hidden-accessible class seems to disappear if a field is invalid. This is using the most recent versions of everything.
  • gene b.
    gene b. over 6 years
    I would add that if you have a background-color or some CSS that Select2 overrides, you need to add !important to your error CSS styles. I had a background-color: yellow for error and Select2 was overriding that.
  • Harun ERGUL
    Harun ERGUL almost 6 years
    Perfect logical answer. Thanks
  • nicolallias
    nicolallias over 5 years
    @dearsina no, unhighliht and success are still distinct from one to another as described in jqueryvalidation.org/validate
  • nicolallias
    nicolallias over 5 years
    Many thanks @Adam, your answer is still compatible to this day!
  • yavor.vasilev
    yavor.vasilev about 5 years
    I just encountered the same issue and in case anyone is wondering why it is occurring and why ignore: [] is fixing it - here is my story: 1. I added "hidden" class to the select which applies display: none to the element 2. This makes Validation to interpret the <select> as type="hidden" 3. Which by default it is not being validated 4. Therefore the need for ignore: []
  • yavor.vasilev
    yavor.vasilev about 5 years
    EDIT: I think the issue comes from the "hidden" keyword, not the css styles because when I change the class to something else the issue is no longer reproducible.
  • user3653474
    user3653474 about 4 years
    When i added ignore:[], it is validating but the form does not submit.
  • user752746
    user752746 about 2 years
    Exactly what I was looking for, worked like a charm. Thank you!