This is code to validate the format of an email address. It does not validate domain names or specific extensions (like .com). It will catch prevent more problems than other freely available code. ("you@yahoo,com" caught, "user24@hotmail..com" caught, " @.net" caught...) You can modify the code however you want, but please do not re-post or redistribute the code without crediting Gentleman's Best Friend Image Consulting Services.

private bool validEmail(string str)
{
str = str.Trim();
// str = trimAll(str); - trimAll is not needed in C#
if (Regex.IsMatch(str, "\\s"))
{
//whitespace in between other characters
return false;
}

if (!(Regex.IsMatch(str, "^.+@.+\\..{2,6}$")))
{
//not in basic email address format
return false;
}

if (str.Length==0)
{
return false;
}

string domain = GetDomainName(str);

//if domain has consecutive periods, it is invalid
if (Regex.IsMatch(domain, "\\.\\."))
{
return false;
}

string extension = GetDomainExtension(domain);
if (!(ValidDomainExtension(extension)))
{
return false;
}

return true;
}

private string trimAll(string sString)
{
//if string is entirely whitespace or empty
if ((!(Regex.IsMatch(sString, "\\S"))) || (sString.Length==0))
{
sString = "";
return sString;
}
string tempString = "";
while ((sString.Substring(0,1) == " ") && (sString.Length>1))
{
// sString = sString.Substring(1, sString.Length); - use a variant of this for VB
sString = sString.Substring(1, sString.Length-1);
}
//sString = tempString;

while (sString.Substring(sString.Length-1, 1) == " ")
{
sString = sString.Substring(0,sString.Length-1);
}
return sString;
}

private string GetDomainName(string sString)
{
int i = sString.Length;

i = sString.LastIndexOf('@');

if (i<1)
{
//no domain name present
return null;
}
//assumes that @ isn't last character
return(sString.Substring(i+1, sString.Length-i-1));
}

private string GetDomainExtension(string sString)
{
int i;
i = sString.LastIndexOf('.');
if (i<1)
{
//no extension present
return null;
}

return(sString.Substring(i+1, sString.Length-i-1));
}

private bool ValidDomainExtension(string sString)
{
int i = sString.Length;

if (i<2)
{
return false;
}

int pos = 0;
while (pos<i)
{
if ( ((sString[pos]>='a') && (sString[pos]<='z')) || ((sString[pos]>='A') && (sString[pos]<='Z')) )
{

}
else
{
//extension contains something other than a letter
return false;
}
pos++;
}

return true;
}