jQuery Select2 Validation

Since my recent post for jQuery TE Validation seems to be popular ( at least for my site 🙂 ) I thought I would demonstrate how to validate another plugin that doesn’t work right out the gate. I’m referring to the Select2 plugin. It is a jQuery replacement for SELECT boxes with a BootStrap type of look. It can product a listbox similar to Facebook’s popular multi-select style. Other options include list item images, searching, sorting (with drag & drop), infinite scrolling, and much more. We will be validating it with the jQuery Validation plugin.

This example uses the following external sources. All of them can be referenced through a Content Delivery Network:
Alternatively, you can go to the plugin sites and retrieve the individual files, or simply install nugets if using .NET.

Now let’s add some markup to the page. The code below covers Select2s that are made in a traditional sense with SELECT tags. If you are creating Select2s with dynamic options (which uses an INPUT[HIDDEN] instead) then I have solution as well. See the second DEMO at the bottom of this tutorial. Here, I’m creating a form with three different types of elements to validate. Each of them have the "required" class which is auto-detected by the jQuery validation plugin. Of course you’re mainly concerned with Select2 but the additional fields are good for a visual comparison when validation fails.
Now let’s add some CSS. Most of this is basic styling besides the myErrorClass portions, which are used to handle validation errors. In our jQuery Validation script we will set it to be our error class. If something fails it will put that class on both the element and an error label. In our script we manipulate the error label to appear behind our element. The !important keyword is needed to override default select2 styling. If all goes well then users should see a striped background on invalid elements as well as a red message describing the error in more detail beneath it.
And finally we add the script. I’ve placed comments throughout to explain the various components:
That’s it! With these adjustments Select2 will have the same look and feel as the rest of your form elements when validating. Leave me a one-liner if you found this useful.

See a DEMO. View this DEMO if loading options dynamically. If this post has helped you then upvote my answer on StackOverflow.

Thanks.