he***********@northnode.se (Henrik Nyberg) wrote in
news:7d**************************@posting.google.c om:
Here's a small method for validating email in C#. It may save
you some time..
public static bool IsValidEmailAddress(string sEmail)
{
if (sEmail == null)
{
return false;
}
int nFirstAT = sEmail.IndexOf('@');
int nLastAT = sEmail.LastIndexOf('@');
if ( (nFirstAT > 0) && (nLastAT == nFirstAT) &&
(nFirstAT < (sEmail.Length - 1)) )
{
// address is ok regarding the single @ sign
return (Regex.IsMatch(sEmail, @"(\w+)@(\w+)\.(\w+)"));
}
else
{
return false;
}
}
Henrik,
You could shorten your code by removing the check for the @ symbol.
It's redundant since the regex will fail if the supplied email
address has more than one @ symbol.
Also, your regex is too restrictive. It will return false for a
valid email address like
go******@governor.ca.gov.
Try this:
public static bool IsValidEmailAddress(string sEmail)
{
if (sEmail == null)
{
return false;
}
else
{
return Regex.IsMatch(sEmail, @"
^
[-a-zA-Z0-9][-.a-zA-Z0-9]*
@
[-.a-zA-Z0-9]+
(\.[-.a-zA-Z0-9]+)*
\.
(
com|edu|info|gov|int|mil|net|org|biz|
name|museum|coop|aero|pro
|
[a-zA-Z]{2}
)
$",
RegexOptions.IgnorePatternWhitespace);
}
}
Hope this helps.
Chris.
-------------
C.R. Timmons Consulting, Inc.
http://www.crtimmonsinc.com/