Select2 checks and forces the user to select at least X items

I'm having trouble trying to do some custom validation using select2 jQuery plugin

I need to get the user to select at least 2 items from the list. The select2 plugin has the maximumSelectionSize property, which allows the user to select up to X elements from the list, but it does not have a "reverse" property. Also the required tag will not work, because I need to select more than one element.

Since I'm working on creating a custom validator with the parsley validation plugin, I will need to know how to get at any moment (usually in the form of submit) the current number (number) of elements selected in the select2 field? Maybe using the val () method?

thanks

0
source share
1 answer

It is decided:

  • Add data-parsley-cantmin = "2" attribute to select2 field

  • Initialize a ParsleyConfig object as follows

    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' } } }; 
+1
source

Source: https://habr.com/ru/post/1209185/


All Articles