Warm tip: This article is reproduced from stackoverflow.com, please click
.net email validation vb.net

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

发布于 2020-03-29 21:02:50

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?

Questioner
Zack Peterson
Viewed
82
83.9k 2011-09-09 04:26

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.