Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate tags using tagit

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.

like image 358
user2862120 Avatar asked Mar 20 '23 15:03

user2862120


1 Answers

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);
        }

    });
like image 149
Chris Avatar answered Mar 28 '23 20:03

Chris