Site Search:
Sign in | Join | Help
4Penny.net

ASP.NET

Notes, Tricks and Tips on ASP.NET Coding

Validate an Email Address

This piece of code will validate an email address.

 


public static bool IsValidEmailAddress(this string s)
    {
        Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
        return regex.IsMatch(s);
    }

Explanation:

^ marks the beginning of the sequence, $ marks the end:

Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");

In between are 4 sequences:

[\w-\.]+

Brackets "[]" surround the range. "\w-" matches a word or a hyphed. "\." matches a period. So, "\w-\." matches words and hyphens followed by periods.  "+" matches one or more of the previous expressions.

@

This is the literal "@" symbol

([\w-]+\.)+

Parens "()" are used to group. "[\w-]+" is one or more "words" or hyphens. "\." matches a literal period. The trailing "+" matches one or more of this group

 

[\w-]{2,4}

"[\w-]" matches a "word" or a hyphen. "{2,4}" allows 2-4 characters in this word


 

Comments

 

John said:

You have very nice site!

 

June 2, 2007 11:22 PM

Leave a Comment

(required)  
(optional)
(required)  
Add

About Steve Gray

Steve is a seasoned (translate: old) developer in VB and ASP.NET. He spends most of his time in Dynamics GP, writing custom mods for consulting firms. Crystal reports, eConnect, VS Tools for Dynamics... anything that comes along.