Select2 validate and force user to select ast least X items
Asked Answered
L

1

0

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

Lamartine answered 13/5, 2014 at 15:12 Comment(0)
L
1

Solved by:

  1. Add data-parsley-cantmin="2" attribute to the select2 field

  2. 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'
            }
        }
    };
    
Lamartine answered 2/7, 2014 at 15:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.