Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array.prototype.every not working inside function?

All,

Please see the following code pen

http://codepen.io/anon/pen/eJNMwJ

I am trying to pass an array of strings into my function called Validate email which iteratively checks over emails to see if they match the regex.

However this function does not seem to work for some reason.

The regex is correct

    var validEmail = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

function validEmailList(emails) {
                console.log("running test 2");
        return emails.every(function (email) {
            validEmail.test(email.trim());
        });
    };

    emails = ['[email protected]', '[email protected]'];
    $('.test1').append(validEmail.test("[email protected]"));
    $('.test2').append(validEmailList(emails));

Nothing seems to be returned from the function, I am expecting a boolean.

like image 891
tomaytotomato Avatar asked Sep 02 '25 14:09

tomaytotomato


1 Answers

The function you pass to every also has to return something.

function validEmailList(emails) {
            console.log("running test 2");
    return emails.every(function (email) {
        return validEmail.test(email.trim());
    });
};

Although if you use arrow syntax, the return is implied:

function validEmailList(emails) {
    return emails.every( email => validEmail.test(email.trim()) );
}
like image 64
Mark Reed Avatar answered Sep 05 '25 05:09

Mark Reed