سؤال

I think I am very close here.

I'm trying to iterate through an array and at each iteration, check whether the value is a valid email address.

The problem is, the loop terminates once it hits either a false or a true. How do I iterate through an array without terminating the loop?

validateForm: function() {

    var emails = $('#email-addresses').val(),
        emailArray = emails.split(',');

    for (var i = 0; i < emailArray.length; i++) {
        if( ! this.validateEmail(emailArray[i].trim())) {
            return false;
        }
        return true;
    };
},

validateEmail: function(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}
هل كانت مفيدة؟

المحلول

It depends on what you want to do here. If you want to hold a result for every check then look at lincb answer. If you want just a true / false about whether all emails were valid then do:

validateForm: function() {

    var emails = $('#email-addresses').val(),
        emailArray = emails.split(',');
    var isValid = true;
    for (var i = 0; i < emailArray.length && isValid == true; i++) {
        if( ! this.validateEmail(emailArray[i].trim())) {
            isValid = false;
        }
    };
    return isValid;
},

نصائح أخرى

In Javascript, return will end the function regardless of any loops. Here is a possible fix:

validateForm: function() {

    var emails = $('#email-addresses').val(),
        emailArray = emails.split(',');
    var returns = new Array();

    for (var i = 0; i < emailArray.length; i++) {
        if( ! this.validateEmail(emailArray[i].trim())) {
            returns[i] = false;
        }
        returns[i] = true;
    }
    return returns;
},
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top