I have a field where a user can submit multiple emails delimited by a comma character. I want JS validation to achieve two things:
- If user tries to submit nothing, they get an alert that they have to enter an email, this WORKS
- If user tries to submit any number of emails where one email is incorrectly formatted, they get an alert that one email has been improperly formatted, and they have to resubmit, this DOES NOT WORK
What happens with #2 is that if I submit something bogus like asddf
as an email, I:
- DO get the alert yay!
- However, the form still gets submitted, BOO
Code:
$("#refer").click(function() {
var input_emails = $('#friend_emails').val();
if (input_emails === "") {
alert("Please enter at least one friend's email to send invites")
return false;
} else {
var parsed_emails = input_emails.split(',');
$.each(parsed_emails, function( index, email_value ) {
var trimmed_email = $.trim(email_value)
var atpos = trimmed_email.indexOf("@");
var dotpos = trimmed_email.lastIndexOf(".");
if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=trimmed_email.length) {
alert(trimmed_email + " " + "is not a valid email format, please correct and resubmit");
return false;
}
});
}
});