I needed a simple email address validation in JavaScript that caught obvious typos. I didn’t really want to use a Regex because I wanted the code to be easy to understand when someone came to read it later, I knew whoever reading would know JavaScript but wasn’t sure if they would know regexes that well. So, a simple function to validate an email address:

  function validateEmail( email ) {
    var at = email.indexOf( "@" );
    var dot = email.lastIndexOf( "\." );
    return email.length > 0 &&
           at > 0 &&
           dot > at + 1 &&
           dot < email.length &&
           email[at + 1] !== "." &&
           email.indexOf( " " ) === -1 &&
           email.indexOf( ".." ) === -1;
  }

and some tests:

  function assert( a, b ) {
    return a == b;
  }

  console.log( assert( validateEmail( "steve@steve.com" ), true ) );
  console.log( assert( validateEmail( "steve@steve.co.uk" ), true ) );
  console.log( assert( validateEmail( "a@a.uk" ), true ) );
  console.log( assert( validateEmail( "bob.ronald.smith@heroku.co" ), true ) );
  console.log( assert( validateEmail( "bob.ronald.smith@heroku.co.uk.com" ), true ) );
  console.log( assert( validateEmail( "UpperCase@ThisIsUP.com" ), true ) );

  console.log( assert( validateEmail( "steve@.com" ), false ) );
  console.log( assert( validateEmail( "steve@aaa.com." ), false ) );
  console.log( assert( validateEmail( "steve@steve" ), false ) );
  console.log( assert( validateEmail( "@steve.com" ), false ) );
  console.log( assert( validateEmail( "steve@" ), false ) );
  console.log( assert( validateEmail( "steve" ), false ) );
  console.log( assert( validateEmail( "steve@steve..com" ), false ) );
  console.log( assert( validateEmail( "steve@.steve.com" ), false ) );
  console.log( assert( validateEmail( "steve@steve..com" ), false ) );