在验证电子邮件地址时,我尝试同时使用 EmailAddressAttribute
来自 System.ComponentModel.DataAnnotations
的类:
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
和 MailAddress
从 System.Net.Mail
类通过做:
bool IsValidEmail(string email)
{
try {
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch {
return false;
}
}
如 C# code to validate email address 中的建议.这两种方法原则上都有效,它们捕获无效的电子邮件地址,例如 user@
,不符合格式 user@host
。
我的问题是这两种方法都没有检测到用户字段中的无效字符,例如 æ、ø 或 å(例如 åge@gmail.com)
。为什么这些字符不返回验证错误有什么原因吗?关于如何在用户字段中加入对无效字符的验证,有人有一个优雅的解决方案吗?
最佳答案
这些字符不是无效的。不寻常,但并非无效。您链接的问题甚至包含您不应该关心的解释。
Full use of electronic mail throughout the world requires that (subject to other constraints) people be able to use close variations on their own names (written correctly in their own languages and scripts) as mailbox names in email addresses.
<子> - RFC 6530 , 2012
关于c# - 针对无效字符验证电子邮件地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37434326/