Validate several Emails within input from the enter key with jquery

Asked

Viewed 647 times

1

I want to use a input to store several emails but I’m having difficulties to implement this in practice.

when placing an email on input the user type enter, to validate the email, if valid add the character ;

How to do this action with jQuery?

$(document).ready(function() {

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="form">
  <input type="text" class="email" id="email">
</form>

1 answer

2


You can use the keyup() to pick up enter event, use the split(';') in the point and comma to take the last email and also use regex below to validate it. The solution below validates the email, if it is valid adds a ; at the end of the input, if not correct 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; });    
}); 

Follows jsfiddle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.