Code for validating email address in C# - validate email

  • Thread starter Thread starter Henrik Nyberg
  • Start date Start date
H

Henrik Nyberg

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;
}
}
 
(e-mail address removed) (Henrik Nyberg) wrote in
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 (e-mail address removed).

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.
 
Back
Top