用于验证电子邮件地址的C#代码 [英] C# code to validate email address

查看:183
本文介绍了用于验证电子邮件地址的C#代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

这是什么? / p>

  bool IsValidEmail(string email)
{
try {
var addr = new System。 Net.Mail.MailAddress(电子邮件);
return addr.Address == email;
}
catch {
return false;
}
}

要澄清一点,问题是询问一个特定的字符串是电子邮件地址的有效表示,而不是电子邮件地址是否是发送邮件的有效目的地。为此,唯一真实的方法是发送一条消息以确认。



请注意,电子邮件地址比您先前假定的更为宽容。这些都是完全有效的形式:




  • cog @ wheel

  • cogwheel the orange@example .com

  • 123 @ $。xyz



对于大多数用例,假的无效对于您的用户来说,要比假的有效更糟糕。这是一个以前是这个问题的接受答案的文章(该答案已被删除)。它有更多的细节和一些其他的想法如何解决问题。



提供健全检查仍然是一个好主意用户体验。假设电子邮件通过验证,您可以通过另一个可以查找已知顶级域的验证器,检查域的MX记录,检查通用域名(gmail.cmo)等的拼写错误然后发出警告,让用户有机会说是的,我的邮件服务器真的允许

What is the most elegant code to validate that a string is a valid email address?

解决方案

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

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 answer to 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 passes validation, you can then pass it through another validator that could look for a known top-level domain, 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

这篇关于用于验证电子邮件地址的C#代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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