KeyLimeTie Blog

Email Address Validator (C#)

By Brian Pautsch – 5/30/2005 1:20:12 PM. Posted to Code Snippets.

If you're building any kind of website that allows users to register, you're going to need an email validator. Some people recommend using a regular expression validator and that works well for most situations, but isn't foolproof. Below is a code snippet of a method that takes in an email address and returns a boolean value.

1public bool IsValidEmail(string strEmail)
2{
3 //Ensure some data is sent in
4 if (strEmail == null || strEmail.Length == 0)
5  return false;
6 //Ensure no spaces exist in the email address
7 if (strEmail.IndexOf(" ") > -1)
8  return false;
9 //Ensure ".@" isn't in the email address
10 if (strEmail.IndexOf(".@") > -1)
11  return false;
12 //Ensure last character is not a period
13 if (strEmail.Substring(strEmail.Length - 1, 1) == ".")
14  return false;
15 //Search for invalid chars
16 if (!System.Text.RegularExpressions.Regex.IsMatch(strEmail, "^[-A-Za-z0-9_@.']+$"))
17  return false;
18 //Search the @ char
19 Int32 i = strEmail.IndexOf("@");
20 //There must be at least three chars after the @
21 if (i <= 0 || i >= strEmail.Length - 3)
22  return false;
23 //Ensure there is only one @ char
24 if (strEmail.IndexOf("@", i + 1) >= 0)
25  return false;
26 //Ensure dot isn't next to @
27 if (strEmail.IndexOf(".@") >= 0 || strEmail.IndexOf("@.") >= 0)
28  return false;
29 //Ensure that the domain portion contains at least one dot
30 Int32 j = strEmail.LastIndexOf(".");
31 //It can't be before or immediately after the @ char
32 if (j < 0 || j <= i + 1)
33  return false;
34
35 //If we get here the, email address if good
36 return true;
37}

Comments

On 10/26/2008 Junior said:
Man... you must user regular expression!

Leave a Comment

Name:
Email:
URL:
Comment:
Security Code:
Type Security Code:

Photos on Flickr

More Photos »

Search Blog


Get Email Updates

Like what you read here at KeyLimeTie? Sign up for our email list!

Subscribe