I'm using the following tag-it plugin: http://widen.github.io/jQuery-Tagit/.
I would like to validate the tags, the input would be email addresses. How can I do this?
My code:
HTML
<div id="editOnClick" class="example">
<ul name="email[]" id="email"></ul>
</div>
JavaScript (jQuery)
$(document).ready(function () {
$('#editOnClick > ul').tagit({
select:true,
triggerKeys:['comma', 'enter', 'space', 'semicolon', 'tab'],
tagSource:"view_email_get_emails.php",
editOnClick:true
beforeTagAdded: function(event, ui) {
return isEmail($('#email').tagit("tags"))}
});
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
});
});
I added my code to JSFiddle.
I'd use the tagsChanged
callback to detect when a new tag has been added, and then validate, and remove it if not valid. I see you've used beforeTagAdded
- I'm not sure where you've got that from? But I don't know the plugin.
The below code does the job. Updated JSFiddle
$(document).ready(function () {
$('#editOnClick > ul').tagit({
select:true,
triggerKeys:['comma', 'enter', 'space', 'semicolon', 'tab'],
tagSource:"view_email_get_emails.php",
editOnClick:true,
tagsChanged: function(tagValue, action, element){
if (action == 'added'){
if (!isEmail(tagValue)){
$('#editOnClick > ul').tagit("remove", 'tag', tagValue);
}
}
});
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With