Validate 2 or more emails in an input

Asked

Viewed 161 times

0

I have a registration that validates the email event focusout in Input. That validation works perfectly. Now the need has arisen to validate multiple emails within the same Input, separating by ";" and how it could treat each email at once?

$("#cobrancaEmail").focusout(function () {
    var valor = $("#cobrancaEmail").val();
    //valida se o email é válido
    if (validaEmailIE(valor)) {
        $("#cobrancaEmail").css({ "border-color": "blue", "padding": "1px" });
        $("#errocobrancaEmail").html("");
    } else {
        $("#cobrancaEmail").css({ "border-color": "red", "padding": "1px" });
        $("#errocobrancaEmail").html("E-mail inválido!");
    }
});


function validaEmailIE(email) {
    var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return regex.test(email);
}
  • What if you, instead of using ID (and thus can only pass 1 email per page to Jquery), use class? All emails that must be validated with the same class, could be passed to Jquery.

1 answer

3


Within the function of the focusout you could add a split and a forEach:

var valor = "[email protected];[email protected];[email protected]"
var contador = 0;

var arr = valor.split(';')

arr.forEach( function (element, index, array) {
    if (!validaEmailIE(element))
        contador++
})

if (contador > 0) {
    // algum email é inválido
} else {
    // todos os email são validos
}

References: Split, foreach

Browser other questions tagged

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