Friday, 11 September 2009

Javascript : Yet an other email address validator.

I was building a Conduct us page the other day and run into the need for a JavaScript e-mail validator. I googled around a bit only to discover that the approaches were so many that I didn't know which one to choose.

So, eventually I did what every hard headed person would do, I sat down amd wrote my own validateEmail function. The code is a merge of ideas coming from the fifth edition of Tom Mergino's and Dori Smith's JavaScript for the World Wide Web, and Anita Sudhakar's approach from SmartWebby.

The resulted code looks like the following :

function validateMail(str)
  var at = "@";
  var dot = ".";
  var atPos = str.indexOf(at);    // position of '@' in the string
  var stringLength = str.length;  // position of '.' after the '@'
  var dotPos = str.indexOf(dot, atPos);
  var invalidChars = "~`/!#$%^&*()+={}[];:";
  var i;
  var badChar;

  // Step 1 Do not allow blank emails
  if ( str == "")
    return false;

  // Step 2 Make sure that the address does not contain invalid characters
  for (i = 0; i < invalidChars.length; i++) {
    badChar = invalidChars.charAt(i);
    if (str.indexOf( badChar) > -1)
      return false;

  // Step 3: Make sure that the @ character is present and
  // that is not the first or the last character of the
  // email address string.
  if (atPos == -1 || atPos == 0 || atPos == stringLength)
     return false;

  // Step 4: Likewise make sure that a dot character exists and that
  // the distance between the @ and . is at least two characters apart
  if (dotPos == -1 || dotPos + 3 > stringLength)
      return false;

  // we have passed all tests let's hope that the email is valid
  return true;

The function should be called from an other function that will retrieve that value of an email filed and test it during form submit. A typical usage would be :

function validateEmailField( fieldID)
  var emailField = document.getElementById( eMailFieldID);
  var status = false;

  if (validateMail(emailField.value))
    status = true;
    alert('Invalid email!');
  return status;

No comments :