如何使用.NET Framework验证电子邮件地址格式? [英] How do I validate email address formatting with the .NET Framework?

查看:223
本文介绍了如何使用.NET Framework验证电子邮件地址格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



.NET框架内置了什么? p>

这样做:

 函数IsValidEmailFormat(ByVal as As String)As Boolean 
尝试
Dim a As New System.Net.Mail.MailAddress(s)
Catch
返回False
结束尝试
返回True
结束功能

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

解决方案

不要打扰自己的验证。 .NET 4.0通过 MailAddress 类。只需使用 MailAddress address = new MailAddress(input),如果它抛出,则无效。如果您的输入作为符合RFC 2822的电子邮件地址规范有任何可能的解释,它将会解析它。上面的正则表达式,甚至是MSDN第一篇文章都是错误的,因为它们未能考虑到显示名称,引用的本地部分,域的域字面值,本地部分的正确点原子规范,邮件地址可以是尖括号,显示名称的多个引用字符串值,转义字符,显示名称中的unicode,注释和最大有效邮件地址长度。我花了三个星期在.NET 4.0 for System.Net.Mail中重新编写邮件地址解析器,并相信我,因为有很多边缘案例,比起正式表达式更难。 .NET 4.0 beta 2中的 MailAddress 类将具有这种改进的功能。



还有一件事,唯一的事情你可以验证邮件地址的格式。您不能验证电子邮件地址实际上是有效的接收电子邮件,而不发送电子邮件到该地址,看看服务器是否接受交付。这是不可能的,虽然有SMTP命令,你可以给邮件服务器尝试验证它,很多时候这些将被禁用或返回不正确的结果,因为这是垃圾邮件发送者查找电子邮件地址的常见方式。


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.

这篇关于如何使用.NET Framework验证电子邮件地址格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆