select2 with parsley validation
There are several reasons your custom validator might not work.
(1) Make sure you are using the correct instructions for the version of parsley.js you are using. I believe the attributes were not prefixed with "data-" for the 1.x versions, but are for the 2.x versions.
(2) The code shown in the stackoverflow answer to which you link must come before you include parsley.js. The code should be different if it comes after you include parsley.js.
Here is what the code should look like if it comes after you include parsley.js:
window.ParsleyValidator
.addValidator('minSelect', function(value, requirement) {
return value.split(',').length >= parseInt(requirement, 10);
}, 32)
.addMessage('en', 'minSelect', 'You must select at least %s.');
(3) It appears that parsley does not validate hidden input elements. So if you are backing your Select2 control with a hidden input (as opposed to a <select>
element), change it to an <input type="text">
element. It will still work with Select2, but parsley will validate it.
<input type="text" id="select" name="x" value=""
data-parsley-minSelect="2"
data-parsley-validate-if-empty="true" />
(4) It appears that by default parsley won't apply your custom validator when the value of the element is empty unless you include the data-parsley-if-empty
attribute.
jsfiddle
I fixed my case just with CSS:
.sel2 .parsley-errors-list.filled {
margin-top: 42px;
margin-bottom: -60px;
}
.sel2 .parsley-errors-list:not(.filled) {
display: none;
}
.sel2 .parsley-errors-list.filled + span.select2 {
margin-bottom: 30px;
}
.sel2 .parsley-errors-list.filled + span.select2 span.select2-selection--single {
background: #FAEDEC !important;
border: 1px solid #E85445;
}
and my select element:
<div class="sel2">
<select id="select-country" class="select2_single form-control" tabindex="-1" required>
...
</select>
</div>
and assign select2:
<script>
$(document).ready(function () {
$(".select2_single").select2({
placeholder: "Select from the list",
allowClear: true
});
});
</script>