

// Validate E-mail Address (JavaScript 1.0 version)
//
//  $Id: email.js,v 1.7 2004/08/25 01:55:11 jreed Exp $
//
//  $Log: email.js,v $
//  Revision 1.7  2004/08/25 01:55:11  jreed
//  Split validEmail into two function - validEmailText can be passed the text value
//
//  Revision 1.6  2004/07/30 21:25:35  jreed
//  Modified validemail() - when invalid select existing value rather than blanking it
//
//  Revision 1.5  2003/10/31 18:20:48  jseverson
//  fixed bug with emails ending in periods. Bug 3603
//
//  Revision 1.4  2002/02/20 18:42:46  nwiggins
//
//  # removes script tags - forces usage as a javascript src include. no php includes
//
//  Revision 1.3  2001/07/18 23:07:57  jneil
//  Fixed some problems.
//
//  Revision 1.2  2001/07/02 06:11:18  vhegde
//  Revision 1.1  2001/05/21 15:53:53  jneil
//  Initial Upload.
//

/**************************************************************
 Description: Email address must be of form a@b.c i.e.,
  there must be at least one character before the @
  there must be at least one character before and after the .
  the characters @ and . are both required
 Dependencies: alltrim, isEmpty, occurs of string.js
**************************************************************/

function validEmail(objFld) {
	if (!validEmailText(objFld.value)) {
    alert("Please enter a valid email address");
    objFld.select();
    return false;
	}
	return true;
}

function validEmailText(strEmailText) {
  var strInvalid = "*?#&^~`'\\[]<>;/:\" ";
  var bAliasedEmail = false;
  var  strAliasedEmail = "";

  var i = 0;
    var  bValid;
  bValid = true;

  strEmailText = alltrim(strEmailText);
  if (isEmpty(strEmailText))
    return true;

  var strEmail = new String(strEmailText);

  // Assumption: if strEmail contains < and >, Email is between < and >
  if (strEmail.indexOf('<') < strEmail.indexOf('>') && strEmail.indexOf('<') >= 0)
  {
    bAliasedEmail = true;
    strAliasedEmail = strEmail;
    strEmail = strEmail.substring(strEmail.indexOf('<')+1,strEmail.indexOf('>'));
  }

  if (strEmail.length < 5)  // check the length
    bValid = false;
  else if (strEmail.lastIndexOf("@") <= 0 || (strEmail.lastIndexOf(".") - strEmail.lastIndexOf("@") <= 1))

// check positions of @ and .

    bValid = false;
  else if (occurs('@', strEmail) > 1) // check if @ occurs more than once
    bValid = false
  else if (strEmail.lastIndexOf(".") == (strEmail.length - 1))
    // check to make sure email doesnt end in period
    bValid = false;
  else  // check if any invalid characters present
  {
    for (i = 0; i < strEmail.length; i++)
      if (strInvalid.indexOf(strEmail.charAt(i)) >= 0)
      {
        bValid = false;
        break;
      }
  }

  if (!bValid) {
    return bValid;
  }

  if (bAliasedEmail)
   this.value = strAliasedEmail;
  else
   this.value = strEmail;

  return bValid;
}


