【问题标题】:How do I validate email address formatting with the .NET Framework?如何使用 .NET Framework 验证电子邮件地址格式?
【发布时间】:2009-08-25 21:22:52
【问题描述】:

我想要一个函数来测试字符串的格式是否像电子邮件地址。

.NET 框架内置了什么来做到这一点?

这行得通:

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

但是,有没有更优雅的方式?

【问题讨论】:

  • 这不正确,试试“someone@somewhere..com”

标签: .net vb.net validation email


【解决方案1】:

不要为自己的验证而烦恼。 .NET 4.0 通过MailAddress 类显着改进了验证。只需使用MailAddress address = new MailAddress(input),如果抛出,则无效。如果您的输入有任何可能的解释为符合 RFC 2822 的电子邮件地址规范,它将按此进行解析。上面的正则表达式,甚至是 MSDN 第一篇文章,都是错误的,因为它们没有考虑到显示名称、引用的本地部分、域的域文字值、本地部分的正确点原子规范、a邮件地址可以是尖括号、显示名称的多个引号字符串值、转义字符、显示名称中的 unicode、cmets 和最大有效邮件地址长度。我花了三周时间在 .NET 4.0 中为 System.Net.Mail 重写邮件地址解析器,相信我,这比仅仅想出一些正则表达式要困难得多,因为有很多边缘情况。 .NET 4.0 beta 2 中的MailAddress 类将具有此改进的功能。

还有一件事,您唯一可以验证的是邮件地址的格式。如果不向该地址发送电子邮件并查看服务器是否接受它进行传递,您将永远无法验证电子邮件地址是否真的可以接收电子邮件。这是不可能的,虽然您可以向邮件服务器提供 SMTP 命令以尝试对其进行验证,但很多时候这些命令将被禁用或返回不正确的结果,因为这是垃圾邮件发送者查找电子邮件地址的常用方法。

【讨论】:

  • 感谢您的回复。我很高兴听到这引起了 Microsoft 的一些关注!但是,为了澄清,您是说最佳实践像我在上面的函数中所做的那样捕获异常?
  • 我想补充一点,捕获异常作为验证数据的一种方式通常是不好的做法。主要原因是性能,特别是在对大量数据执行此类验证时,但通常它只是被认为是不好的做法。对于像电子邮件地址这样简单的事情,我会选择使用 RegEx。
  • 但是,这似乎只允许“part1@part2”而不需要“.com”等顶级域。
  • 很久没写这个了,但它不应该让part2只是一个随机词,它可以是点原子或域文字,域文字可以只是“part2 " 但必须包含在 "[" 和 "]" 中才能有效。点原子必须有一个“。”在它的前面和后面是一个合法的点原子字符。规范在这里:tools.ietf.org/html/rfc2822#page-17 此外,它可能会将不带括号的域文字解释为域文字,并为您添加括号。不记得了,但听起来像是我会做的事情。
  • 我也可以输入 myname@mail*.com 并且它接受它,所以这不起作用:(
【解决方案2】:

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

此示例方法调用 Regex.IsMatch(String, String) 方法来验证字符串是否符合正则表达式模式。

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

【讨论】:

  • 这似乎是确定的。但是,我仍然更愿意在 System.Net.Mail 中的某个地方找到这样的内置函数。 :(
  • 这没有考虑到电子邮件地址的许多不同的边缘情况,其中最重要的是引用的本地部分。还有许多其他有效的非字母数字字符也是此正则表达式不允许的。我知道这是一篇 MSDN 文章,但它是错误的。我在 System.Net.Mail.MailAddress 中为 .NET 4.0 重新编写了地址解析,使其更加健壮,并考虑了这些因素。有关更多详细信息,请参阅下面的答案。
  • @JeffTucker 这是RFC822 compliant regex
  • 正则表达式将拒绝使用超过 9 个字符的顶级域的有效地址,
  • 这不适用于像 me.love.gmail@gmail.com 这样的邮件
【解决方案3】:
    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

【讨论】:

  • 答案后面应该有一些解释,而不是代码 sn-p 以便更好地理解
  • 请在您的回答中添加一些解释。
  • 这里的问题是您可以将两个有效的电子邮件地址与一个无效的分隔符串在一起,它不会捕获错误。
  • 抄袭 Jeff Tucker 的回答,五年过去了。
【解决方案4】:
'-----------------------------------------------------------------------

'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

【讨论】:

    【解决方案5】:

    你首先必须通过输入错误的符号来限制用户,你可以通过使用文本框 KeyPress 事件来做到这一点

    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
    

    上面的代码只允许用户输入a-z(small), 0 to 9(digits), @,., _

    在使用文本框控件的验证事件使用正则表达式验证电子邮件 ID 之后

    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
    

    【讨论】:

      【解决方案6】:

      您应该使用 Regular Expressions 来验证电子邮件地址。

      【讨论】:

      • 所以你可能会遇到 2 个问题 :)
      • 互联网和这个网站对用正则表达式解决这个问题的尝试充满了不正确。除非您是正则表达式向导电子邮件向导,否则请不要考虑它。 (我是,我做到了,但决定不这样做。)
      【解决方案7】:

      另一个检查电子邮件是否有效的功能:

      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
      

      使用方法:

      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
      

      【讨论】:

        【解决方案8】:

        您可以使用正则表达式来执行此操作。

        已经写了很多关于它的文章;当我在谷歌搜索“正则表达式验证电子邮件地址”时出现了这个问题:Find or Validate an Email Address

        【讨论】:

        • 同意航海者。现在我有两个问题。
        • 这些比 MSDN 文章中的正则表达式更好,但在许多边缘情况下仍然失败。
        【解决方案9】:

        在这种情况下,我已经测试了批准的“答案”,它似乎不符合实际有效电子邮件地址的规范。经过多次头痛后,我发现这个正则表达式比微软做得更好。

        "(?:(?:\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*)"
        

        我已经使用一个简单的应用程序将其格式化为 vb 字符串。太糟糕的堆栈溢出对成为“编码存储库”更感兴趣,而不是获得问题的完整答案。

        【讨论】:

        • 可怜可怜的开发者,不得不为这个庞然大物进行故障排除。
        【解决方案10】:

        像“address@localhost”和“user@192.168.1.2”这样的电子邮件实际上是有效地址,您可以通过运行自己的电子邮件服务器来测试这些地址(通常也可以通过修改主机文件来完成)。 但是,对于完整的解决方案:

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

        【讨论】:

          【解决方案11】:
           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
          

          【讨论】:

            猜你喜欢
            • 2019-05-07
            • 1970-01-01
            • 1970-01-01
            • 2014-06-27
            • 2016-06-24
            • 2016-11-03
            • 2022-01-14
            相关资源
            最近更新 更多