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