问题
I'm having some trouble trying to do some custom validation with a select2 jQuery plugin
I need to force user to select at least 2 items from the list. The select2 plugin has a property maximumSelectionSize that allows user to select up to X items from the list, but it does not have the "inverse" property. Also the required tag won't work because I need user to select more than one item.
As I'm working developing a custom validator with parsley validation plugin, I'd need to know how to get at any moment (commonly at form submit) the current quantity (number) of items chosen in a select2 field? Maybe with val() method?
Thanks
回答1:
Solved by:
Add data-parsley-cantmin="2" attribute to the select2 field
Initialize the ParsleyConfig object as following
window.ParsleyConfig = { validators: { cantmin: { fn: function (value, requirement) { //return value !== requirement; if ($("#campoprofesionales").val()) if($("#campoprofesionales").val().length > 1) {return true} else {return false} }, priority: 32 } }, i18n: { en: { cantmin: 'You have to select at least %s items from the list' }, es: { cantmin: 'Tiene que seleccionar al menos %s items de la lista' } } };
来源:https://stackoverflow.com/questions/23635129/select2-validate-and-force-user-to-select-ast-least-x-items