用于验证电子邮件地址的 C# 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1365407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# code to validate email address
提问by leora
What is the most elegant code to validate that a string is a valid email address?
验证字符串是有效电子邮件地址的最优雅的代码是什么?
采纳答案by Cogwheel
What about this?
那这个呢?
bool IsValidEmail(string email)
{
try {
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch {
return false;
}
}
To clarify, the question is asking whether a particular string is a valid representation of an e-mail address, not whether an e-mail address is a valid destination to send a message. For that, the only real way is to send a message to confirm.
澄清一下,问题是询问特定字符串是否是电子邮件地址的有效表示,而不是电子邮件地址是否是发送消息的有效目的地。为此,唯一真正的方法是发送消息进行确认。
Note that e-mail addresses are more forgiving than you might first assume. These are all perfectly valid forms:
请注意,电子邮件地址比您最初想象的更宽容。这些都是完全有效的形式:
- cog@wheel
- "cogwheel the orange"@example.com
- 123@$.xyz
- 齿轮@wheel
- “齿轮橙色”@example.com
- 第123话
For most use cases, a false "invalid" is much worse for your users and future proofing than a false "valid". Here's an article that used to be the accepted answerto this question (that answer has since been deleted). It has a lot more detail and some other ideas of how to solve the problem.
对于大多数用例,虚假的“无效”比虚假的“有效”对您的用户和未来证明更糟糕。这是一篇文章,曾经是这个问题的公认答案(该答案已被删除)。它有更多的细节和一些关于如何解决问题的其他想法。
Providing sanity checks is still a good idea for user experience. Assuming the e-mail address is valid, you could look for known top-level domains, check the domain for an MX record, check for spelling errors from common domain names (gmail.cmo), etc. Then present a warning giving the user a chance to say "yes, my mail server really does allow as an email address."
提供健全性检查对于用户体验来说仍然是一个好主意。假设电子邮件地址有效,您可以查找已知的顶级域,检查域中的 MX 记录,检查常见域名 (gmail.cmo) 中的拼写错误等。然后向用户发出警告有机会说“是的,我的邮件服务器确实允许作为电子邮件地址。”
As for using exception handling for business logic, I agree that is a thing to be avoided. But this is one of those cases where the convenience and clarity may outweigh the dogma.
至于对业务逻辑使用异常处理,我同意这是应该避免的事情。但这是方便和清晰可能超过教条的情况之一。
Besides, if you do anything else with the e-mail address, it's probably going to involve turning it to a MailAddress. Even if you don't use this exact function, you will probably want to use the same pattern. You can also check for specific kinds of failure by catching different exceptions: null, empty, or invalid format.
此外,如果您对电子邮件地址执行任何其他操作,则可能需要将其转换为 MailAddress。即使您不使用这个确切的函数,您也可能希望使用相同的模式。您还可以通过捕获不同的异常来检查特定类型的失败:空、空或无效格式。
Per Stuart's comment, this compares the final address with the original string instead of always returning true. MailAddress tries to parse a string with spaces into "Display Name" and "Address" portions, so the original version was returning false positives.
根据 Stuart 的评论,这会将最终地址与原始字符串进行比较,而不是始终返回 true。MailAddress 尝试将带有空格的字符串解析为“显示名称”和“地址”部分,因此原始版本返回误报。
--- Further reading ---
--- 进一步阅读 ---
Documentation for System.Net.Mail.MailAddress
System.Net.Mail.MailAddress 的文档
回答by Kibbee
Personally, I would say that you should just make sure there is an @ symbol in there, with possibly a . character. There's many regexes you could use of varying correctness, but I think most of these leave out valid email addresses, or let invalid ones through. If people want to put in a fake email address, they will put in a fake one. If you need to verify that the email address is legit, and that the person is in control of that email address, then you will need to send them an email with a special coded link so they can verify that it indeed is a real address.
就我个人而言,我会说你应该确保那里有一个 @ 符号,可能还有一个 . 特点。您可以使用许多具有不同正确性的正则表达式,但我认为其中大多数会遗漏有效的电子邮件地址,或者让无效的电子邮件地址通过。如果人们想输入一个假的电子邮件地址,他们就会输入一个假的。如果您需要验证电子邮件地址是否合法,并且此人控制着该电子邮件地址,那么您需要向他们发送一封带有特殊编码链接的电子邮件,以便他们可以验证它确实是真实地址。
回答by Mauricio Scheffer
Email address validation is not as easy as it might seem. It's actually theoretically impossible to fully validate an email address using just a regular expression.
电子邮件地址验证并不像看起来那么容易。实际上,仅使用正则表达式完全验证电子邮件地址在理论上是不可能的。
Check out my blog postabout it for a discussion on the subject and a F# implementation using FParsec. [/shameless_plug]
查看我的博客文章,了解有关该主题的讨论以及使用 FParsec 的 F# 实现。[/shameless_plug]
回答by Noon Silk
To be honest, in production code, the best I do is check for an @
symbol.
老实说,在生产代码中,我所做的最好的事情就是检查@
符号。
I'm never in a place to be completely validating emails. You know how I see if it was really valid? If it got sent. If it didn't, it's bad, if it did, life's good. That's all I need to know.
我永远无法完全验证电子邮件。你知道我怎么看它是否真的有效吗?如果寄过去了。如果没有,那很糟糕,如果有,生活就很好。这就是我需要知道的全部。
回答by Matthew Lock
I find this regex to be a good trade off between checking for something more than just the @ mark, and accepting weird edge cases:
我发现这个正则表达式是在检查不仅仅是 @ 标记的东西和接受奇怪的边缘情况之间的一个很好的权衡:
^[^@\s]+@[^@\s]+(\.[^@\s]+)+$
It will at least make you put something around the @ mark, and put at least a normal looking domain.
它至少会让你在@ 标记周围放置一些东西,并至少放置一个看起来正常的域。
回答by Joe Caffeine
If you really and I mean really want to know if an email address is valid...ask the mail exchanger to prove it, no regex needed. I can provide the code if requested.
如果您真的而且我的意思是真的想知道电子邮件地址是否有效...请邮件交换器证明这一点,不需要正则表达式。如果需要,我可以提供代码。
General steps are as follows: 1. does email address have a domain name part? (index of @ > 0) 2. using a DNS query ask if domain has a mail exchanger 3. open tcp connection to mail exchanger 4. using the smtp protocol, open a message to the server using the email address as the reciever 5. parse the server's response. 6. quit the message if you made it this far, everything is good.
一般步骤如下: 1. 邮箱地址有域名部分吗?(@> 0 的索引) 2. 使用 DNS 查询询问域是否有邮件交换器 3. 打开与邮件交换器的 tcp 连接 4. 使用 smtp 协议,使用电子邮件地址作为接收者向服务器打开消息 5.解析服务器的响应。6. 到此为止就退出消息,一切都很好。
This is as you can imagine, very expensive time wise and relies on smtp, but it does work.
这是您可以想象的,非常昂贵的时间,并且依赖于 smtp,但它确实有效。
回答by Efran Cobisi
Generally speaking, a regular expression to validate email addresses is not an easy thing to come up with; at the time of this writing, the syntax of an email address must follow a relatively high number of standards and implementing all of them within a regular expression is practically unfeasible!
一般来说,验证电子邮件地址的正则表达式不是一件容易的事情。在撰写本文时,电子邮件地址的语法必须遵循相对较多的标准,并且在正则表达式中实现所有这些标准实际上是不可行的!
I highly suggest you to try our EmailVerify.NET, a mature .NET library which can validate email addresses following allof the current IETF standards (RFC 1123, RFC 2821, RFC 2822, RFC 3696, RFC 4291, RFC 5321 and RFC 5322), tests the related DNS records, checks if the target mailboxes can accept messages and can even tell if a given address is disposable or not.
我强烈建议您尝试我们的EmailVerify.NET,这是一个成熟的 .NET 库,它可以按照所有当前的 IETF 标准(RFC 1123、RFC 2821、RFC 2822、RFC 3696、RFC 4291、RFC 5321 和 RFC 5322)验证电子邮件地址,测试相关的 DNS 记录,检查目标邮箱是否可以接受消息,甚至可以判断给定的地址是否是一次性的。
Disclaimer: I am the lead developer for this component.
免责声明:我是该组件的首席开发人员。
回答by David Silva Smith
I took Phil's answer from #1 and created this class.
Call it like this: bool isValid = Validator.EmailIsValid(emailString);
我从#1 中获取了 Phil 的答案并创建了这个类。像这样调用它:bool isValid = Validator.EmailIsValid(emailString);
Here is the class:
这是课程:
using System.Text.RegularExpressions;
public static class Validator
{
static Regex ValidEmailRegex = CreateValidEmailRegex();
/// <summary>
/// Taken from http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
/// </summary>
/// <returns></returns>
private static Regex CreateValidEmailRegex()
{
string validEmailPattern = @"^(?!\.)(""([^""\r\]|\[""\r\])*""|"
+ @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
+ @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
return new Regex(validEmailPattern, RegexOptions.IgnoreCase);
}
internal static bool EmailIsValid(string emailAddress)
{
bool isValid = ValidEmailRegex.IsMatch(emailAddress);
return isValid;
}
}
回答by imjosh
This is an old question, but all the answers I've found on SO, including more recent ones, are answered similarly to this one. However, in .Net 4.5 / MVC 4 you can add email address validation to a form by adding the [EmailAddress] annotation from System.ComponentModel.DataAnnotations, so I was wondering why I couldn't just use the built-in functionality from .Net in general.
这是一个古老的问题,但我在 SO 上找到的所有答案,包括最近的答案,都与这个答案类似。但是,在 .Net 4.5 / MVC 4 中,您可以通过添加 System.ComponentModel.DataAnnotations 中的 [EmailAddress] 注释来向表单添加电子邮件地址验证,所以我想知道为什么我不能只使用 .网一般。
This seems to work, and seems to me to be fairly elegant:
这似乎有效,在我看来相当优雅:
using System.ComponentModel.DataAnnotations;
class ValidateSomeEmails
{
static void Main(string[] args)
{
var foo = new EmailAddressAttribute();
bool bar;
bar = foo.IsValid("[email protected]"); //true
bar = foo.IsValid("[email protected]"); //true
bar = foo.IsValid("[email protected]"); //true
bar = foo.IsValid("[email protected]"); //true
bar = foo.IsValid("fdsa"); //false
bar = foo.IsValid("fdsa@"); //false
bar = foo.IsValid("fdsa@fdsa"); //false
bar = foo.IsValid("fdsa@fdsa."); //false
//one-liner
if (new EmailAddressAttribute().IsValid("[email protected]"))
bar = true;
}
}
回答by Poyson1
I think the best way is as follow:
我认为最好的方法如下:
public static bool EmailIsValid(string email)
{
string expression = "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
if (Regex.IsMatch(email, expression))
{
if (Regex.Replace(email, expression, string.Empty).Length == 0)
{
return true;
}
}
return false;
}
You can have this static function in a general class.
您可以在通用类中使用此静态函数。