How to make jQuery validation engine works well for select2()

select2_1

When we use select2 to prettify selector , the jQuery validation engine will do not work well for it. A lot of people have to do custom validation function to hand over it.

It’s very troublesome, is there any way to solve this problem?

Select2 library make the original selector hidden, and validation engine can not work for hidden element, so first is make the <select> visible, then the validation engine can see it. The second is we need to make the selector element hidden for us, there are about 2 ways to do, such as set it’s opacity into “0”, or make it’s height/width as “0px”, actually we need both.

Below is the code example:

 

 

The following two tabs change content below.
Wang Weiqiang is a senior web developer, and professional on ASP.NET, MVC, C#, Python, SQL Server, HTML5, Javascript, also interesting in machine learning and related algorithm.

Latest posts by Wang Weiqiang (王维强) (see all)

Wang Weiqiang is a senior web developer, and professional on ASP.NET, MVC, C#, Python, SQL Server, HTML5, Javascript, also interesting in machine learning and related algorithm.

Posted in Javascript Tagged with: , ,
5 comments on “How to make jQuery validation engine works well for select2()
  1. Zolek says:

    I’ve got a problem with that solution, in my project data is validated on form submission, and while once this select is empty (while required) that little error popup stays without the posiibility to remove it on clicking on it.

    • Wang Weiqiang (王维强) says:

      You mean the error popup shows before submission or does not work?
      can you send your screen shot to my email?

  2. Maykel Esser says:

    Ive got the same error :/

    My JS code:

    if($(‘.select2’).exists())
    {
    $(“.select2”).select2({
    width: “100%”,
    closeOnSelect: true
    });
    }
    $.each($(“.select2-container”), function (i, n)
    {
    $(n).next().show().fadeTo(0, 0).height(“0px”).css(“left”, “auto”); // make the original select visible for validation engine and hidden for us
    $(n).prepend($(n).next());
    $(n).delay(500).queue(function () {
    $(this).removeClass(“validate[required]”); //remove the class name from select2 container(div), so that validation engine dose not validate it
    $(this).dequeue();
    });
    });

    And my HTML code:

    Escolha…
    [1] Empresa
    [2] Produtos
    [3] Serviços
    [4] Localização

    The select shows a validation popup, but even filling the field, doesnt dissapear.

1 Pings/Trackbacks for "How to make jQuery validation engine works well for select2()"

Leave a Reply to Maykel Esser Cancel reply

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

*

Categories

Recent Posts

Related Posts