I’d like to limit number characters of string in select2 in ten (10) characters, for example:
"apple", is valid.. has 5 characters
"book", is valid.. has 4 characters
"Incomprehensibilities", is invalid... has 21 characters, permited max 10 characters
I have the select2 code but I don’t know how to limit the number of characters
$("#customer_tag_ids").select2({
maximumSelectionLength: 5,
multiple: true,
tags: true,
tokenSeparators: [',', ' '],
createTag: function (params) {
if (params.term.match(/^(?![d ])[a-zd ]*$/i)) {
// Return null to disable tag creation
return {
id: params.term,
text: params.term,
tag: true
}
}
return null;
},
language: {
maximumSelected: function (e) {
return I18n.t('customers.alert.limit_max');
},
inputTooShort: function (e) {
return I18n.t('customers.alert.limit_min');
},
noResults: function(){
return I18n.t('customers.alert.not_result_found');
}
},
});
2
Answers
You can achieve this by setting the
maxlength
attribute of the class.select2-search__field
in theselect2:open
event.e.g.
I modified your
createTag
option to prevent user input text that has more than 10 chars. Also I added adiv
tag below to give a warning message whenever the user want to create a new tag.Another solution
At first I thought that we can use the event select2:selecting
That means you can catch the event
$('#customer_tag_ids').on('select2:selecting, (event) => { // do something })
and then use the method
event.preventDefault()
to prevent selecting the value.But then I realized you’ve already have some conditions inside the
creatTag
option, and you may want to check the condition and show the message to the new tags only, so I end up with the below solution.