How do I validate email address formatting with the .NET Framework?

'-----------------------------------------------------------------------

'Creater : Rachitha Madusanka

'http://www.megazoon.com

'[email protected]

'[email protected]

'Web Designer and Software Developer

'@ http://www.zionx.net16.net

'-----------------------------------------------------------------------




Function ValidEmail(ByVal strCheck As String) As Boolean
    Try
        Dim bCK As Boolean
        Dim strDomainType As String


        Const sInvalidChars As String = "!#$%^&*()=+{}[]|\;:'/?>,< "
        Dim i As Integer

        'Check to see if there is a double quote
        bCK = Not InStr(1, strCheck, Chr(34)) > 0
        If Not bCK Then GoTo ExitFunction

        'Check to see if there are consecutive dots
        bCK = Not InStr(1, strCheck, "..") > 0
        If Not bCK Then GoTo ExitFunction

        ' Check for invalid characters.
        If Len(strCheck) > Len(sInvalidChars) Then
            For i = 1 To Len(sInvalidChars)
                If InStr(strCheck, Mid(sInvalidChars, i, 1)) > 0 Then
                    bCK = False
                    GoTo ExitFunction
                End If
            Next
        Else
            For i = 1 To Len(strCheck)
                If InStr(sInvalidChars, Mid(strCheck, i, 1)) > 0 Then
                    bCK = False
                    GoTo ExitFunction
                End If
            Next
        End If

        If InStr(1, strCheck, "@") > 1 Then 'Check for an @ symbol
            bCK = Len(Left(strCheck, InStr(1, strCheck, "@") - 1)) > 0
        Else
            bCK = False
        End If
        If Not bCK Then GoTo ExitFunction

        strCheck = Right(strCheck, Len(strCheck) - InStr(1, strCheck, "@"))
        bCK = Not InStr(1, strCheck, "@") > 0 'Check to see if there are too many @'s
        If Not bCK Then GoTo ExitFunction

        strDomainType = Right(strCheck, Len(strCheck) - InStr(1, strCheck, "."))
        bCK = Len(strDomainType) > 0 And InStr(1, strCheck, ".") < Len(strCheck)
        If Not bCK Then GoTo ExitFunction

        strCheck = Left(strCheck, Len(strCheck) - Len(strDomainType) - 1)
        Do Until InStr(1, strCheck, ".") <= 1
            If Len(strCheck) >= InStr(1, strCheck, ".") Then
                strCheck = Left(strCheck, Len(strCheck) - (InStr(1, strCheck, ".") - 1))
            Else
                bCK = False
                GoTo ExitFunction
            End If
        Loop
        If strCheck = "." Or Len(strCheck) = 0 Then bCK = False

ExitFunction:
        ValidEmail = bCK
    Catch ex As ArgumentException
        Return False
    End Try
    Return ValidEmail
End Function

Don't bother with your own validation. .NET 4.0 has significantly improved validation via the MailAddress class. Just use MailAddress address = new MailAddress(input) and if it throws, it's not valid. If there is any possible interpretation of your input as an RFC 2822 compliant email address spec, it will parse it as such. The regexes above, even the MSDN article one, are wrong because they fail to take into account a display name, a quoted local part, a domain literal value for the domain, correct dot-atom specifications for the local part, the possibility that a mail address could be in angle brackets, multiple quoted-string values for the display name, escaped characters, unicode in the display name, comments, and maximum valid mail address length. I spent three weeks re-writing the mail address parser in .NET 4.0 for System.Net.Mail and trust me, it was way harder than just coming up with some regular expression since there are lots of edge-cases. The MailAddress class in .NET 4.0 beta 2 will have this improved functionality.

One more thing, the only thing you can validate is the format of the mail address. You can't ever validate that an email address is actually valid for receiving email without sending an email to that address and seeing if the server accepts it for delivery. It is impossible and while there are SMTP commands you can give to the mail server to attempt to validate it, many times these will be disabled or will return incorrect results since this is a common way for spammers to find email addresses.


    Public Function ValidateEmail(ByVal strCheck As String) As Boolean
        Try
            Dim vEmailAddress As New System.Net.Mail.MailAddress(strCheck)
        Catch ex As Exception
            Return False
        End Try
        Return True
    End Function

MSDN Article: How to: Verify That Strings are in Valid E-Mail Format

This example method calls the Regex.IsMatch(String, String) method to verify that the string conforms to a regular expression pattern.

Function IsValidEmailFormat(ByVal s As String) As Boolean
    Return Regex.IsMatch(s, "^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$")
End Function