Reputation: 311
i am using bootstrap tags input in my site. basically what i am trying to do is, ask user to type urls into a text field, now if the text is valid url then only convert it into tag otherwise don't.
is there any way to process text before converting into tags?
any help would be appriciated.
Thanks
Upvotes: 4
Views: 3515
Reputation: 595
Bootstrap tags have beforeItemAdd event which triggered just before an item gets added. Bootstrap tags
$('input').on('beforeItemAdd', function(event) {
/* Validate url */
if (/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(event.item)) {
event.cancel = false;
} else {
event.cancel = true;
}
});
Upvotes: 5
Reputation: 18028
If your input id is "tag-input", all you have to do is use a beforeItemAdd
callback provided by the library itself like so:
$('#tag-input').on('beforeItemAdd', function(event) {
var tag = event.item;
if(true){ //if tag is not a url or process other text conditions.
event.cancel = true
}
});
If you don't set event.cancel
to false, the add
will go through.
You can check the documentation on this method here.
Also , as it is clear in this case that documentation does not say how to cancel the event. In such cases its simple enough to just check the code itself. I this case this code in the plugins github repo makes it plenty clear how to use this option.
Upvotes: 0
Reputation: 16575
Bootstrap Tags Input have a hidden
input before convert to tags
you find it by following code:
$(".bootstrap-tagsinput input[type="text"]").keyup(function(){
// do your validation
});
you can see it by get an inspect element
in your page. it will convert to tags
after you press enter button
you can do your validation until it's on hidden input.
It will be there:
<div class="bootstrap-tagsinput">
<span class="tag label label-info">Test<span data-role="remove"></span></span>
<input type="text" style="width: 7em;" size="1"> // here is!
</div>
Upvotes: 2