I have this script where it loops through an array and its supposed to check if each of the values within the array is an email with this function:
function isEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
Supposed to look through array:
$.each(arrayEmail,function(i){
var checkEmail = isEmail(arrayEmail[i]);
if(checkEmail != false){
alert(arrayEmail[i]);
var message = $('#sendMsg textarea.emailMsg').val();
$.ajax({
type:'post',
url:'ajax_inviteMsg.php',
data: 'to='+$.trim(arrayEmail[i])+'&message='+message,
success: function(data){
alert(data);
}
});
}
});
The alert(arrayEmail[i]);
after checking if email if false or not only displays first value, which tells me that it only iterates through the if statement one, however, I've tested the emails and should be working doesn't get passed through that if statement.
If the alert right after the each function, it iterates through the values corretly.
Again, the emails are true and should be iterating through the if statement as true.
I just want to know what I'm doing wrong that it only passes the if statement once if there's multiple values in the array.
Thanks
EDIT
I also have this before the each function
<div>test@gmail.com, fresh@hotmail.com</div>
var emails = $('div').text();
var arrayEmail = emails.split(',');
After you split text of div element your array becomes this: element0 = "test@gmail.com" element1 = " fresh@hotmail.com"
2nd element has leading space and fails to match regular expression.
Try with this div: test@gmail.com,fresh@hotmail.com without space and you will understand.
On the end trim string before validating it.