Select2 validate and force user to select ast least X items

大憨熊 提交于 2019-12-13 06:43:39

问题


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:

  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'
            }
        }
    };
    


来源:https://stackoverflow.com/questions/23635129/select2-validate-and-force-user-to-select-ast-least-x-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!