Select2验证并强制用户选择最少X个项目 [英] Select2 validate and force user to select ast least X items
问题描述
尝试使用select2 jQuery插件进行一些自定义验证时遇到麻烦
I'm having some trouble trying to do some custom validation with a select2 jQuery plugin
我需要强制用户从列表中至少选择 2 个项目. select2插件具有属性 maximumSelectionSize ,该属性允许用户从列表中选择最多X个项目,但不具有"inverse"属性.同样,所需的标签也无法使用,因为我需要用户选择多个项目.
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.
在使用 parsley 验证插件开发自定义验证器时,我需要知道如何获取在任何时候(通常是在表单提交时)在select2字段中选择的当前项目数量(数量)吗?也许使用val()方法?
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?
谢谢
推荐答案
解决方案:
-
向select2字段添加 data-parsley-cantmin ="2" 属性
按如下所示初始化ParsleyConfig对象
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'
}
}
};
这篇关于Select2验证并强制用户选择最少X个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!