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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With