简体   繁体   中英

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

I want a function to test that a string is formatted like an email address.

What comes built-in with the .NET framework to do this?

This works:

Function IsValidEmailFormat(ByVal s As String) As Boolean
    Try
        Dim a As New System.Net.Mail.MailAddress(s)
    Catch
        Return False
    End Try
    Return True
End Function

But, is there a more elegant way?

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.

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
'-----------------------------------------------------------------------

'Creater : Rachitha Madusanka

'http://www.megazoon.com

'jewandara@gmail.com

'jewandara@hotmail.com

'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
    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

you first have to restrict user by entering wrong symbols, you can do this by using textbox KeyPress event

Private Sub txtemailid_KeyPress(ByVal sender As System.Object, 
                                ByVal e As System.Windows.FormsKeyPressEventArgs) Handles txtemailid.KeyPress

    Dim ac As String = "@"
    If e.KeyChar <> ChrW(Keys.Back) Then
        If Asc(e.KeyChar) < 97 Or Asc(e.KeyChar) > 122 Then
            If Asc(e.KeyChar) <> 46 And Asc(e.KeyChar) <> 95 Then
                If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
                    If ac.IndexOf(e.KeyChar) = -1 Then
                        e.Handled = True

                    Else

                        If txtemailid.Text.Contains("@") And e.KeyChar = "@" Then
                            e.Handled = True
                        End If

                    End If


                End If
            End If
        End If

    End If

End Sub

the above code will only allow user to input az(small), 0 to 9(digits), @,., _

and after using validating event of textbox control to validate the email id using regular expression

Private Sub txtemailid_Validating(ByVal sender As System.Object, 
                                  ByVal e As System.ComponentModel.CancelEventArgs) 
    Handles txtemailid.Validating

    Dim pattern As String = "^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"


    Dim match As System.Text.RegularExpressions.Match = Regex.Match(txtemailid.Text.Trim(), pattern, RegexOptions.IgnoreCase)
    If (match.Success) Then
        MessageBox.Show("Success", "Checking")
    Else
        MessageBox.Show("Please enter a valid email id", "Checking")
        txtemailid.Clear()
    End If
End Sub

您应该使用正则表达式来验证电子邮件地址。

Another function to check that the email is valid or not :

Public 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

How to use it:

Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
    If e.KeyCode = Keys.Enter Then
        If TextBox2.Text = "" Then
            MsgBox("Write Down Your email and Press Enter") : TextBox2.Select()
        Else

            If ValidEmail(TextBox2.Text) Then ' to check if the email is valid or not
                   'do whatever
            Else
                MsgBox("Please Write Valid Email")
                TextBox2.Select()
            End If
        End If
    End If
End Sub

You could use a Regex to do this.

There have been written a lot of articles about it; this came up when I searched google for 'regex to validate email address': Find or Validate an Email Address .

I have tested the approved 'answer' in this case and it does not seem to adhere to the specifications of what actually is a valid email address. After many headaches I found this regex which does a much better job than Microsoft does.

"(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]" +
")+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|""(?:[^\""\r\\]|\\.|(?:(?:\r\n)?[ \t]))*""(?:(?:" +
"\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(" +
"?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|""(?:[^\""\r\\]|\\.|(?:(?:\r\n)?[ " +
"\t]))*""(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\0" +
"31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\" +
"](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+" +
"(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:" +
"(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z" +
"|(?=[\[""()<>@,;:\\"".\[\]]))|""(?:[^\""\r\\]|\\.|(?:(?:\r\n)?[ \t]))*""(?:(?:\r\n)" +
"?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\" +
"r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[" +
" \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)" +
"?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t]" +
")*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[" +
" \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*" +
")(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]" +
")+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)" +
"*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+" +
"|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|""(?:[^\""\r\\]|\\.|(?:(?:\r\n)?[ \t]))*""(?:(?:\r" +
"\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:" +
"\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|""(?:[^\""\r\\]|\\.|(?:(?:\r\n)?[ \t" +
"]))*""(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031" +
"]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](" +
"?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?" +
":(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?" +
":\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?" +
":(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|""(?:[^\""\r\\]|\\.|(?:(?:\r\n)?" +
"[ \t]))*""(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\"".\[\] " +
"\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|""(?:[^\""\r\\]|" +
"\\.|(?:(?:\r\n)?[ \t]))*""(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>" +
"@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|""" +
"(?:[^\""\r\\]|\\.|(?:(?:\r\n)?[ \t]))*""(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t]" +
")*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\" +
""".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?" +
":[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[" +
"\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\"".\[\] \000-" +
"\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|""(?:[^\""\r\\]|\\.|(" +
"?:(?:\r\n)?[ \t]))*""(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;" +
":\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([" +
"^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\""" +
".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\" +
"]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\" +
"[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\" +
"r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] " +
"\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]" +
"|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\"".\[\] \0" +
"00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|""(?:[^\""\r\\]|\\" +
".|(?:(?:\r\n)?[ \t]))*""(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@," +
";:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|""(?" +
":[^\""\r\\]|\\.|(?:(?:\r\n)?[ \t]))*""(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*" +
"(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\""." +
"\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[" +
"^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\]" +
"]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*(" +
"?:(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\" +
""".\[\]]))|""(?:[^\""\r\\]|\\.|(?:(?:\r\n)?[ \t]))*""(?:(?:\r\n)?[ \t])*)(?:\.(?:(" +
"?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[" +
"\[""()<>@,;:\\"".\[\]]))|""(?:[^\""\r\\]|\\.|(?:(?:\r\n)?[ \t]))*""(?:(?:\r\n)?[ \t" +
"])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t" +
"])+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?" +
":\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|" +
"\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:" +
"[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\"".\[\" +
"]]))|""(?:[^\""\r\\]|\\.|(?:(?:\r\n)?[ \t]))*""(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)" +
"?[ \t])*(?:@(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""" +
"()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)" +
"?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>" +
"@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[" +
" \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@," +
";:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t]" +
")*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\" +
""".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?" +
"(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[""()<>@,;:\\""." +
"\[\]]))|""(?:[^\""\r\\]|\\.|(?:(?:\r\n)?[ \t]))*""(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:" +
"\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[" +
"""()<>@,;:\\"".\[\]]))|""(?:[^\""\r\\]|\\.|(?:(?:\r\n)?[ \t]))*""(?:(?:\r\n)?[ \t])" +
"*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])" +
"+|\Z|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\" +
".(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z" +
"|(?=[\[""()<>@,;:\\"".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(" +
"?:\r\n)?[ \t])*))*)?;\s*)"

I have already formatted it as a vb string using a simple application. Too bad stack overflow is more interested in being a 'coding repository' than having the complete answer for the problem.

EMails like "address@localhost" and "user@192.168.1.2" are actually valid addresses and you can test these by running your own email server (usually done by modifying the host file as well). For a complete solution, however:

''' <summary>
''' METHODS FOR SENDING AND VALIDATING EMAIL
''' </summary>
''' <remarks></remarks>
Public Class email

    ''' <summary>
    ''' check if email format is valid
    ''' </summary>
    ''' <param name="emailAddress">[required] Email address.</param>
    ''' <param name="disallowLocalDomain">[optional] Allow headers like "@localhost"?</param>
    ''' <param name="allowAlerts">[optional] Enable error messages?</param>
    ''' <returns>Returns true if email is valid and false otherwise.</returns>
    ''' <remarks></remarks>
    Public Shared Function isValid(ByVal emailAddress As String,
                                   Optional ByVal disallowLocalDomain As Boolean = True,
                                   Optional ByVal allowAlerts As Boolean = True
                                   ) As Boolean
        Try
            Dim mailParts() As String = emailAddress.Split("@")
            If mailParts.Length <> 2 Then
                If allowAlerts Then
                    MsgBox("Valid email addresses are formatted [sample@domain.tld]. " &
                           "Your address is missing a header [i.e. ""@domain.tld""].",
                           MsgBoxStyle.Exclamation, "No Header Specified")
                End If
                Return False
            End If
            If mailParts(mailParts.GetLowerBound(0)) = "" Then
                If allowAlerts Then
                    MsgBox("Valid email addresses are formatted [sample@domain.tld]. " &
                           "The username portion of the e-mail address you provided (before the @ symbol) is empty.",
                           MsgBoxStyle.Exclamation, "Invalid Email User")
                End If
                Return False
            End If
            Dim headerParts() As String = mailParts(mailParts.GetUpperBound(0)).Split(".")
            If disallowLocalDomain AndAlso headerParts.Length < 2 Then
                If allowAlerts Then
                    MsgBox("Valid email addresses are formatted [sample@domain.tld]. " &
                           "Although addresses formatted like [sample@domain] are valid, " &
                           "only addresses with headers like ""sample.org"", ""sample.com"", and etc. " &
                           "[i.e. @domain.org] are accepted.",
                           MsgBoxStyle.Exclamation, "Invalid Header")
                End If
                Return False
            ElseIf headerParts(headerParts.GetLowerBound(0)) = "" Or
                   headerParts(headerParts.GetUpperBound(0)) = "" Then
                If allowAlerts Then
                    MsgBox("Valid email addresses are formatted [sample@domain.tld]. " &
                           "Your header """ & mailParts(mailParts.GetUpperBound(0)) & """ is invalid.",
                           MsgBoxStyle.Exclamation, "Invalid Header")
                End If
                Return False
            End If
            Dim address As MailAddress = New MailAddress(emailAddress)
        Catch ex As Exception
            If allowAlerts Then
                MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Invalid Email Address")
            End If
            Return False
        End Try
        Return True
    End Function

End Class 'email'

I think by avoiding running into the exception as often as you can, and relying on it as a fallback could be a good low effort, high trust happy place. Im not very experienced with regex and I dont trust it very much so I wanted to offer a solution that is improved from yours... I added a check that looks for a min length of 5, and that it contains "@" because it is one of the only consistent things in emails and should catch anything very obviously not an email. while catching the exception is "bad" and can cause the method to run slow if your application seems to run into more complex exceptions and you have to care about resource usage this should either help you get close to your solution, while also being robust up to the library standard of microsoft. Note that the The real minimum for emails is 3 i think "a@b" but looking at practical data i used 5 in my code

Function IsValidEmailFormat(ByVal pMaybeEmail As String) As Boolean
    If pMaybeEmail.Contains("@") andAlso pMaybeEmail.Length() > 5 Then 

        ' most likely an email, but just in case
        Try
            Dim validEmail As New System.Net.Mail.MailAddress(pMaybeEmail)
            return True
        Catch
            return False
        End Try

    End If 
    Return False
End Function

在此处输入图像描述

 Public Shared Function ValidEmailAddress(ByVal emailAddress As String, ByRef errorMessage As String) As Boolean
        If emailAddress.Length = 0 Then
            errorMessage = "E-mail address is required."
            Return False
        End If
        If emailAddress.IndexOf("@") > -1 Then
            If (emailAddress.IndexOf(".", emailAddress.IndexOf("@")) > emailAddress.IndexOf("@")) AndAlso emailAddress.Split(".").Length > 0 AndAlso emailAddress.Split(".")(1) <> "" Then
                errorMessage = ""
                Return True
            End If
        End If
        errorMessage = "E-mail address must be valid e-mail address format."
        Return False
    End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM