JavaScript Email Validation

Yesterday I needed to find a way to fix an issue where participants who were signing up for an enewsletter were getting an unfriendly error if they didn’t fill out a valid email in the email field before they submitted the form. The unfriendly notification actually took them to a new webpage from our email campaign company. It looked sloppy and wasn’t a seamless user experience. I thought about a way to fix this and came up with a simple solution. Instead of just trying to figure out a way to get the user to stay on our site, I figured with email validation the user would stay on our site and get reminded that they input an invalid email address. The code I found was located on w3schools and looks like this:

<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>

The top JavaScript should go in the <head> of your document but it will probably work as long as you stick it on the page somewhere. That is the JavaScript code that is making sure that the email address is in the correct format and is in the layout x@x.xxx. You can change the pop up text” Not a valid e-mail address” to say whatever you want it to but watch out for putting quotes in there.

The bottom part is the form fields. The important thing to have there are form name=”myForm”, onsubmit=”return validateForm();” and name=”email”. You can see where those text calls match in the JavaScript up top.

After I implemented the code on the page and tested with a non-valid email address, I got a nice friendly pop up error telling me that I needed to enter a valid email address. No more awkward site visits to our email campaign company.