Posts

Showing posts from October, 2008

Validating an email address with a regular expression

Below is a quick and dirty post on how to use the C# regular expression library to validate an email address. The regular expression stuff is located in the System.Text.RegularExpression namespace. So somewhere in my class I use the code below. Now you don't have to do class member variables. You could just do all this code in a function. I however will be doing multiple validations so I don't want to be destroying/creating multiple objects during the life of my class. You have to create your regular expression and then use that expression when creating the RegEx object. private string _expression = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" + @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; private Regex _validEmailRegEx = new RegEx( _expression ); Then in my class I define a function that uses the RegEx object to validate an email address being