34

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?

Zack Peterson
  • 56,055
  • 78
  • 209
  • 280

12 Answers12

65

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.

Dan Herbert
  • 99,428
  • 48
  • 189
  • 219
Jeff Tucker
  • 3,387
  • 22
  • 19
  • 1
    Thank you for responding. I'm glad to hear that this has gotten some attention from Microsoft! But, just to clarify, you're saying that the best practice *is* to catch an exception as I've done in the function above? – Zack Peterson Aug 27 '09 at 14:43
  • Yes, you must catch the FormatException that it throws if the address is invalid. Your code is correct. – Jeff Tucker Aug 27 '09 at 16:55
  • One last thing: System.Net.Mail has gotten all kinds of attention from Microsoft for .NET 4.0. You can see what we've improved in my post on the NCL blog: http://blogs.msdn.com/ncl/archive/2009/08/06/what-s-new-in-system-net-mail.aspx – Jeff Tucker Aug 28 '09 at 10:09
  • 5
    I would like to add that it is generally bad practice to catch an exception as a way of validating data. Mainly the reason is performance especialy when performing such validation over large sets of data but in generally it is just considered bad practice. For things as simple as email addresses I would opt for using a RegEx instead. – jpierson Mar 11 '11 at 22:22
  • 10
    However, this seems to allow simply "part1@part2" without requiring the top-level domain of ".com" or whatnot. – Jeff Handley Apr 01 '11 at 06:08
  • 1
    A long time since I wrote this, but it shouldn't allow part2 to just be a random word, it can either be a dot atom OR a domain literal, and domain literals could just be "part2" but must be enclosed in "[" and "]" in order to be valid. A dot-atom must have a "." in it and be preceded and followed by a single legal dot-atom character. The spec is here: http://tools.ietf.org/html/rfc2822#page-17 Also, it's possible that it will interpret a domain literal without brackets as a domain literal and will add the brackets for you. Don't remember for sure, but sounds like something I would do. – Jeff Tucker Apr 11 '11 at 22:53
  • 3
    I can also type myname@mail*.com and it accepts it, so this doesn't work :( – MojoDK May 07 '13 at 13:45
  • 2
    I'd like to add that email address like "sample@localhost" is a valid address, which is why this format is allowed. If you want to check the validity of the @host part, you can use the split function and check if the length of the resulting array is greater than 1. First, split using "@", check if the resulting array has a length of 2, then split the second array element using "." and check if the resulting array is greater than 1. – RJBaytos Sep 28 '16 at 06:09
  • Sorry, but there are a lot of things wrong with comments here. @RJBaytos, "@localhost" is not a valid email address, as accepted globally. What would a practical use be for a system to email itself without a proper host and top level domain? @ Jeff Tucker, there are still many things wrong with using the MailAddress object for simple validation purpose. One being, if you want to simply validate a proper simple email address (name@host.com) and say leave off the top level domain (name@host), it sees it as valid, since items other than email addresses can be used for a .Net MailAddress. – Chase Oct 13 '20 at 15:05
  • @Chase For public facing systems that provides an email form, setting up an 'address@localhost' in the email server gets the job done. That said, it is true that it is not a "globally accepted" address. Even in email validations in PHP for instance, address@localhost is not accepted as a valid email. That said, it totally depends on the type of system being developed. – RJBaytos Jan 03 '21 at 08:18
  • @Chase Nevertheless, address@localhost is a valid address since it is a legitimate address that the host can use to send email to itself. Or you can just redirect the external domain name to the localhost in the hosts file if you don't want the server to be way too dependent on the remote DNS service. – RJBaytos Jan 03 '21 at 08:37
  • Also, this is why even if filter_var('username@localhost', FILTER_VALIDATE_EMAIL) returns false on the server-side, the validations on the client side's tag does let it pass. It's because the address is in an acceptable format. – RJBaytos Jan 03 '21 at 08:55
  • Yes you can not validate an email address exists without sending, but you can easily test if the domain is active. that plus validation of syntax gives you a got 80+% confidence – AquaAlex Jul 06 '21 at 16:57
11

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
Zack Peterson
  • 56,055
  • 78
  • 209
  • 280
Edmundo
  • 183
  • 5
  • That seems definitive. But, I'd still prefer to find such a function built-in and squirreled away somewhere within System.Net.Mail. :( – Zack Peterson Aug 25 '09 at 21:57
  • 11
    This fails to take into account many different edge cases with email addresses, the most significant of which is a quoted local part. There are plenty of other non-alphanumeric characters which are valid as well that this regex doesn't allow for. I know it's an MSDN article but it's wrong. I re-wrote address parsing for .NET 4.0 in System.Net.Mail.MailAddress to be a lot more robust and take these things into account. See my answer below for more detail. – Jeff Tucker Aug 25 '09 at 22:24
  • @JeffTucker This is the [RFC822 compliant regex](http://ex-parrot.com/~pdw/Mail-RFC822-Address.html). – user17753 Sep 06 '12 at 15:13
  • The regex will reject valid addresses that use top-level domains with more than 9 characters, – Paul B. Feb 29 '16 at 09:59
  • This not work with mail like me.love.gmail@gmail.com – Jorge Rocha Jan 14 '20 at 23:42
  • It worked just fine with me.love.gmail@gmail.com. Jorge is incorrect. Perhaps the OP corrected the code. – pianocomposer Oct 06 '21 at 17:45
6
    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
texwil
  • 61
  • 1
  • 1
3
'-----------------------------------------------------------------------

'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
Lance Roberts
  • 22,383
  • 32
  • 112
  • 130
2

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 a-z(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
Spontifixus
  • 6,570
  • 9
  • 45
  • 63
1

You should use Regular Expressions to validate email addresses.

Lucky
  • 4,787
  • 9
  • 40
  • 50
  • 21
    so you can have 2 problems :) – Esteban Küber Aug 25 '09 at 21:36
  • 3
    The Internet and this site are shock full of *incorrect* attempts at solving this with a regex. Unless you are a regex wizard **and** an email wizard, don't even think about it. (I am, and I did, and decided not to.) – tripleee Sep 13 '11 at 06:39
1

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
Community
  • 1
  • 1
0

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.

Roman Boiko
  • 3,576
  • 1
  • 25
  • 41
Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
0

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.

codemonkeyliketab
  • 320
  • 1
  • 2
  • 17
0

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'
RJBaytos
  • 71
  • 1
  • 8
0

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

enter image description here

-1
 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
drneel
  • 2,887
  • 5
  • 30
  • 48