I am lazy. Well, not a ‘couch-potato-couldn’t-be-bothered-to-shower lazy’, but more of a ‘let’s-not-make-things-too-complicated’ lazy. So when it came time to figure out a way to make sure an email address was really an email address on an html submit form, I decided to concentrate on a few things that all valid email addresses have, namely the ‘@’ symbol, and a ‘.’. I know, some of you will say that user@localhost is a perfectly valid email address, and you are quite right about that. It’s not routable on the internet, though, so I am not worried about those types of addresses.
As I am sure you know, most email addresses are in the following format:
bunch.of.letters@somedomain.com
What I decided to do, to keep things simple, of course, was to test for an @ symbol, then test for a . somewhere after the @ symbol. I did this using the indexOf() and lastIndexOf() functions in javascript.
$(".email").click(function(){
var email = $("#useremail").val();
// check for @ sign
if (email.indexOf('@') > 0) {
// check to see if there is a period after the @ sign
if (email.lastIndexOf('.') >= email.indexOf('@')) {
// everything is ok
// if no username, insert 'anonymous'
if ($("#username").val() == '') { $("#username").val("anonymous"); }
var dataString = "userName=" + $("#username").val() + '&userEmail=' + $("#useremail").val();
$("#output").html("<img src='imgs/ajax-loader.gif'>");
$("#output").fadeIn(3000).delay(3000);
$.ajax({
type: "POST",
url: "php/sendit.php",
data: dataString,
success: function() { setOutput("Email sent!"); }
});
return false;
} else { setOutput("Invalid Email!"); }
} else { setOutput("Invalid Email!"); }
});
});
The important lines are 14 and 16. Line 14 checks to make sure that there is an @ symbol somewhere in the string. If the indexOf value is > 0, then the next check is done. We use lastIndexOf() when testing for the . because periods may appear before the @ symbol in a valid email address. So to avoid bouncing those types of addresses, we look for a period with an index value greater than the index value of the @. Hence, we know that there is an @ symbol and a period in the email address and we can consider it valid.

