Skip to content

Instantly share code, notes, and snippets.

Created June 25, 2012 22:27
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Workaround for using jquery-validation-engine with select2 for 'required' validation
<script type="text/javascript">
// This is a workaround for using jquery-validation-engine with select2 for 'required' validation
// Since the _required validator for jquery-validation-engine uses .val() to see
// if there's anything in the input, we can hijack .val() for the container created by select2\
// and redirect it to the value of the hidden element
// jquery-validation-engine throws an error if the thing we're validating doesn't have an id
// so we'll put one on the container created by select2 (that way, the positioning of the prompts
// will be correct)
$('#mySelector').select2('container').attr('id', 'mySelectorValidate');
// Mostly lifted from
$.fn.setTypeForHook = function () {
this.each(function () {
this.type = 'mySelector';
return this;
// With the 'type' set, we can add a valhook to redirect .val() for the container
// to .val() from the hidden input
// select2 sets up its own 'val' method, so we'll use that in this case
$.valHooks['mySelector'] = {
get: function (el) {
return $('#mySelector').select2("val");
set: function (el, val) {
$('#mySelector').select2("val", val);
<div class="mySelectorContainer" id="tcuSelection">
<!-- select2 will copy the validate[required] class to the container it creates -->
<input type="hidden" id="mySelector" name="TCUId" class="mySelector validate[required]"/>
Copy link

Hi! I've find only your suggest over the net for this problem, but I should need an explanation.

Could you give an example how to apply your code if I have an ListBox where I have apply the jquery select2 ?

Copy link

I resolved this doing the following, in select2.js - line 341:

if (this.indexOf("select2-") !== 0 && this !== 'validate[required]') {

Copy link

@playmono will this hack work for select2 version 4 (beta)
I could not find the line in select2.js

Copy link

i am use the select2.min.js ; so what are the changes i do

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment