Como validar a formatação do endereço de E-mail com the.NET Framework?
Quero UMA função para testar que uma cadeia de caracteres é formatada como um endereço de E-mail.
O que vem embutido com o framework. NET para fazer isso?isto funciona:
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
Mas, existe uma maneira mais elegante?
11 answers
MailAddress
classe. Basta usar MailAddress address = new MailAddress(input)
e se atirar, não é válido. Se houver qualquer interpretação possível da sua entrada como uma especificação de endereço de E-mail compatível RFC 2822, ela irá analisá-la como tal. As expressões anteriores, mesmo o artigo 1 do MSDN, estão erradas porque não levam em conta um nome de visualização, uma parte local citada, um valor literal de domínio para o domínio, ponto-átomo correcto 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. Passei três semanas a reescrever o analisador de endereços de E-mail no.NET 4.0 para o System.Net.Mail e acredite em mim, foi muito mais difícil do que inventar alguma expressão regular, uma vez que há muitos casos extremos. A classe MailAddress
do. NET 4.0 beta 2 irá tenha esta funcionalidade melhorada.
Mais uma coisa, a única coisa que podes validar é o formato do endereço de E-mail. Você nunca pode validar que um endereço de E-mail é realmente válido para receber e-mail sem enviar um e-mail para esse endereço e ver se o servidor o Aceita para entrega. É impossível e, embora existam comandos SMTP que possa dar ao servidor de E-mail para tentar validá - lo, muitas vezes estes serão desactivados ou Irão devolver resultados incorrectos, uma vez que este é um forma comum para os spammers para encontrar endereços de E-mail.
MSDN artigo: Como verificar se as cadeias de caracteres estão num formato de E-Mail válido
Este método de exemplo chama a Regex.Método IsMatch (String, String) para verificar se a string está em conformidade com um padrão de expressão regular.
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
'[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
Primeiro tem de restringir o utilizador ao introduzir símbolos errados; poderá fazê-lo se usar o evento de teclado do campo de texto
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
O código acima só permitirá ao Utilizador introduzir a-z(pequeno), 0 a 9 (dígitos), @,., _
E depois de usar a validação do controlo do evento da caixa de texto para validar o id do E-mail com a expressão regular
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
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
Deverá usar Expressões Regulares para validar os endereços de E-mail.
Outra função para verificar se o e-mail é válido ou não:
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
Como usá-lo:
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
Podias usar uma réplica para fazer isto.
Foram escritos muitos artigos sobre este assunto; isto surgiu quando procurei no google por 'regex para validar o endereço de E-mail': Encontre ou valide um endereço de E-Mail .
Eu testei a 'resposta' aprovada neste caso e parece não aderir às especificações do que realmente é um endereço de E-mail válido. Depois de muitas dores de cabeça eu encontrei este regex que faz um trabalho muito melhor do que a Microsoft faz.
"(?:(?:\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*)"
Já o formatei como um texto vb usando uma aplicação simples. É pena que o overflow stack esteja mais interessado em ser um 'repositório de codificação' do que ter a resposta completa para o problema.
E-mails como " address@localhost "e" [email protected] " são na verdade endereços válidos e você pode testá-los executando seu próprio servidor de E-mail (geralmente feito modificando o arquivo host também). No entanto, para uma solução completa:
''' <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 [[email protected]]. " &
"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 [[email protected]]. " &
"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 [[email protected]]. " &
"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 [[email protected]]. " &
"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'
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