Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate multiple emails with JavaScript

I have these two functions:

validateEmail: function(value) {
    var regex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return (regex.test(value)) ? true : false;
}

validateEmails: function(string) {

    var self = shareEmail;
    var result = string.replace(/\s/g, "").split(/,|;/);

        for(var i = 0;i < result.length;i++) {
            if(!self.validateEmail(result[i])) {
                return false;
            } else {               
            return true;
        }
    }
}

The problem is that when I test the email like this if(!self.validateEmails(multipleEmails)) { i get true or false based only on the first email in the string, but I want to test for any email in the string.

Thank you!

like image 878
Adrian Florescu Avatar asked Aug 24 '12 08:08

Adrian Florescu


1 Answers

The problem is your if/else block; You are returning under both conditions. Which means that it leaves the function after evaluating only one element.

I've modified validateEmails to demonstrate what you probably want to do:

validateEmail: function(value) {
    var regex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    return (regex.test(value)) ? true : false;
}

validateEmails: function(string) {
    var self = shareEmail;
    var result = string.replace(/\s/g, "").split(/,|;/);

    for(var i = 0;i < result.length;i++) {
        if(!self.validateEmail(result[i])) {
            return false;
        }
    }

    return true;
}
like image 168
Lucas Green Avatar answered Oct 09 '22 06:10

Lucas Green