Reputation: 2397
Is there anyway to define a set of "allowed" characters for user input? For e.g. alphanumeric input only. Can't seem to find it within the official documentation
Upvotes: 4
Views: 4082
Reputation: 1135
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.
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).
So, my final code is (for contribution purpose):
$('my-select2').on('select2-open',function(e){
var input = $(this).select2("dropdown").find('.select2-input');
// ...
});
Upvotes: 0
Reputation: 481
You can accomplish this using the createSearchChoice option, which allows you to define a custom function to create tags from user input. To not allow tags containing other than alphanumeric characters, the select2 should be initialized as:
$("#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. 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.
Update:
As of select2 version ~ 4.0
this function is now called createTag
Upvotes: 4
Reputation: 1
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. 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
Upvotes: 0