[dba-VB] C#: Validate e-mail address

Gustav Brock Gustav at cactus.dk
Sat Aug 9 11:54:46 CDT 2008


Hi all

I needed to validate the format of user entered e-mail addresses and couldn't find a good method, except some RegEx at Microsoft.
So I had to run my own, but wonder if anything better exists.

MailAddress is used for first level validation as this later will be used to create the e-mails:

using System.Net.Mail;

        private static bool IsMailAddress(string address, out string cleanedAddress)
        {
            cleanedAddress = String.Empty;
            try
            {
                MailAddress mailAddress = new MailAddress(address.Trim());
                // MailAddress validated the address. 
                // However, even one char only for Host will be accepted.
                // Extract user and host for further validation.
                bool isAddress = false;
                string displayName = mailAddress.DisplayName;
                // Strip internal spaces from user and host string.
                string user = mailAddress.User.Replace(" ", String.Empty);
                string host = mailAddress.Host.Replace(" ", String.Empty);
                // Build basic mail address.
                string baseAddress = (user + "@" + host).ToLower();
                // Check that Host contains a domain too.
                // Expanding on the method described here: http://support.microsoft.com/kb/308252 
                System.Text.RegularExpressions.Regex mailRegex = 
                    new System.Text.RegularExpressions.Regex("(?<user>[^@]+)@(?<host>[^.]+).(?<domain>[^.]+).");
                System.Text.RegularExpressions.Match match = mailRegex.Match(baseAddress);
                Console.WriteLine(
                    match.Groups["user"].Value.ToString() + "@" +
                    match.Groups["host"].Value.ToString() + "." +
                    match.Groups["domain"].Value.ToString());
                isAddress = match.Success;
                if (isAddress)
                {
                    // Return formatted email address.
                    if (displayName.Length == 0)
                    {
                        // Basic mail address only.
                        cleanedAddress = baseAddress;
                    }
                    else
                    {
                        // Full address including Display Name.
                        cleanedAddress = @"""" + displayName + @""" <" + baseAddress + @">";
                    }
                }
                return isAddress;
            }
            catch
            {
                return false;
            }
        }

The trick is that MailAddress is somewhat flexible regarding accepted strings and will _clean_ these, thus you very easily can return the cleaned string. Of course, you can turn this into a small class if you like.

Here's a basic method to use it with the ErrorProvider when validating a TextBox:

        private void textBoxEmailAddress_Validating(object sender, CancelEventArgs e)
        {
            TextBox textBox = (TextBox)sender;
            string errorDescription = String.Empty;
            string cleanedAddress = String.Empty;
            string address = textBox.Text;
            if (textBox.Text.Equals(String.Empty))
            {
                errorDescription = "Please enter an e-mail address";
            }
            else if (!IsMailAddress(address, out cleanedAddress))
            {
                errorDescription = "The format of the address is not correct";
            }
            else
            {
                if (!cleanedAddress.Equals(address))
                {
                    textBox.Text = cleanedAddress;
                }
            }
            errorProvider1.SetError(textBox, errorDescription);
        }

/gustav





More information about the dba-VB mailing list