Validate several Emails inside input to enter from the enter key with jquery

1

I want to use a input to store multiple emails but I'm having trouble deploying this in practice.

When placing an email in input the user press enter, to validate the email, if valid add the character ;

How to do this with jQuery?

$(document).ready(function() {

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="form">
  <input type="text" class="email" id="email">
</form>
    
asked by anonymous 01.10.2015 / 22:37

1 answer

2

You can use keyup() to get enter event, use split(';') in the semicolon to get the last email and you can also use regex below to validate it. The solution below validates the email, if it is valid add a ; at the end of the input, if it is not correct it does nothing:

function verificarEAdicionarEmail() {

    var arrayEmail = $('#email').val().split(';');    
    var eEmailValido = validaEmail(arrayEmail[arrayEmail.length - 1]);

    if(eEmailValido) {
        $('#email').val('');

        arrayEmail.forEach(function(email){
            $('#email').val(($('#email').val() + email + ';'));
        });
    }
}

function validaEmail(email) {
    if(/^([\w\-]+\.)*[\w\- ]+@([\w\- ]+\.)+([\w\-]{2,3})$/.test(email))
        return true;
    return false;
}

$(document).ready(function() {

    $('#email').keyup(function(event){
        if(event.which == 13)
            verificarEAdicionarEmail();
    });

    $('form').submit(function(){ return false; });    
}); 

Follow jsfiddle .

    
02.10.2015 / 01:40