JavaScript: Email Validation (pt. 1)

Tech: JavaScript

Challenge: validating emails for a POST form… regex is always painful… what is best practice? I believe this is an incredibly easy & fast choice. Note, not my code but I will be using it everywhere!

Code (drop in <head>):


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;




For the form:

<form name=”myForm” onsubmit=”return validateForm()”>

Email: <input type=”text” name=”email>