简体   繁体   English

jquery select2插件正则表达式允许的字符?

[英]jquery select2 plugin regex for allowed characters?

Is there anyway to define a set of "allowed" characters for user input? 有没有为用户输入定义一组“允许”字符? For eg alphanumeric input only. 仅用于例如字母数字输入。 Can't seem to find it within the official documentation 似乎无法在官方文档中找到它

You can accomplish this using the createSearchChoice option, which allows you to define a custom function to create tags from user input. 您可以使用createSearchChoice选项完成此操作,该选项允许您定义自定义函数以从用户输入创建标记。 To not allow tags containing other than alphanumeric characters, the select2 should be initialized as: 要不允许包含除字母数字字符以外的标记,select2应初始化为:

$("#mySelect").select2({
            createSearchChoice: function(term) {
                if(term.match(/^[a-zA-Z0-9]+$/g))
                    return { id: term, text: term };
            },
            formatNoMatches: "Enter valid format text"})

If the user is typing text that contains non-alphanumeric characters, the dropdown below the select2 will show no matches. 如果用户正在键入包含非字母数字字符的文本,则select2下方的下拉列表将不显示匹配项。 It's not necessary to specify a custom formatNoMatches but it is more helpful for the user than the default "No matches found" to figure out why their input isn't being accepted. 没有必要指定自定义formatNoMatches,但它对用户比默认的“找不到匹配项”更有帮助,以找出他们的输入未被接受的原因。

Update: 更新:

As of select2 version ~ 4.0 this function is now called createTag 从select2 version~ 4.0此函数现在称为createTag

I didn't find anything about put a mask/regex on the input where you type. 我没有找到任何关于在您输入的输入上放置掩码/正则表达式的信息。 But you can do it on the 'open' event provided by select2. 但你可以在select2提供的'open'事件上做到这一点。 Something like this: 像这样的东西:

$('select of the select2 input or select').on('select2-open',function(e){
    // apply your mask on this element -> $('.select2-input')
});

Hope it helps you. 希望它能帮到你。 Bye 再见

Today I was finding a way to apply a custom mask on the input that appear in the dropdown (select2 v3), and I found this topic. 今天我找到了一种方法,在下拉列表中显示的输入上应用自定义蒙版(select2 v3),我找到了这个主题。

After some research on official doc I saw the method select2("container") , and looking the source code I found select2("dropdown") (not present on doc). 经过对官方文档的一些研究后,我看到方法select2("container") ,并查找源代码,我发现select2("dropdown") (不在doc上)。

So, my final code is (for contribution purpose): 所以,我的最终代码是(出于贡献目的):

$('my-select2').on('select2-open',function(e){
    var input = $(this).select2("dropdown").find('.select2-input');
    // ...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM