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:
- There is a required
select box
which is converted toselect2
- You click the submit and the error shows that the select box is required.
- You select some option from select 2.
- 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'
});
Related videos on Youtube
user2323711
Updated on October 18, 2020Comments
-
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 about 9 yearsMy 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 over 8 years$("select").on("select2-close", function (e) { $(this).valid(); });
-
Tsukasa about 8 yearsany chance of an update for select2 4.0.x. Doesn't seem to work.
-
SolaceBeforeDawn over 7 yearsThat is so simple - yet couldn't find any mention in the docs for Select2
-
e_i_pi about 7 yearsFantastic, fixed my problem after a long time trying myself! +1
-
Ahmad Mobaraki almost 7 yearsup vote for :
$select.on('change', function() { $(this).trigger('blur'); });
-
Adam over 6 years@Tsukasa you find an update in my answer stackoverflow.com/a/46953372/2311074
-
Nirav Thakar over 6 yearsIt's my pleasure Damith
-
dearsina over 6 yearsIf 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 theselect2-hidden-accessible
class seems to disappear if a field is invalid. This is using the most recent versions of everything. -
gene b. over 6 yearsI would add that if you have a
background-color
or some CSS that Select2 overrides, you need to add!important
to yourerror
CSS styles. I had abackground-color: yellow
forerror
and Select2 was overriding that. -
Harun ERGUL almost 6 yearsPerfect logical answer. Thanks
-
nicolallias over 5 years@dearsina no, unhighliht and success are still distinct from one to another as described in jqueryvalidation.org/validate
-
nicolallias over 5 yearsMany thanks @Adam, your answer is still compatible to this day!
-
yavor.vasilev about 5 yearsI 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 about 5 yearsEDIT: 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 about 4 yearsWhen i added ignore:[], it is validating but the form does not submit.
-
user752746 about 2 yearsExactly what I was looking for, worked like a charm. Thank you!