验证字符串是否是有效的电子邮件地址的最优雅的代码是什么?
当前回答
.net 4.5增加了System.ComponentModel.DataAnnotations.EmailAddressAttribute
你可以浏览EmailAddressAttribute的源代码,这是它内部使用的正则表达式:
const string pattern = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$";
其他回答
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.
最优雅的方法是使用. net的内置方法。
这些方法:
都是经过考验的。我在自己的专业项目中使用了这些方法。 内部使用正则表达式,这是可靠和快速的。 由微软为c#编写。没有必要做重复的工作。 返回bool类型的结果。True表示邮件有效。
适用于。net 4.5及以上版本的用户
将此引用添加到项目中:
System.ComponentModel.DataAnnotations
现在你可以使用下面的代码:
(new EmailAddressAttribute().IsValid("youremailhere@test.test"));
使用实例
下面是一些需要声明的方法:
protected List<string> GetRecipients() // Gets recipients from TextBox named `TxtRecipients`
{
List<string> MethodResult = null;
try
{
List<string> Recipients = TxtRecipients.Text.Replace(",",";").Replace(" ", "").Split(';').ToList();
List<string> RecipientsCleaned = new List<string>();
foreach (string Recipient in RecipientsCleaned)
{
if (!String.IsNullOrWhiteSpace(Recipient))
{
RecipientsNoBlanks.Add(Recipient);
}
}
MethodResult = RecipientsNoBlanks;
}
catch//(Exception ex)
{
//ex.HandleException();
}
return MethodResult;
}
public static bool IsValidEmailAddresses(List<string> recipients)
{
List<string> InvalidAddresses = GetInvalidEmailAddresses(recipients);
return InvalidAddresses != null && InvalidAddresses.Count == 0;
}
public static List<string> GetInvalidEmailAddresses(List<string> recipients)
{
List<string> MethodResult = null;
try
{
List<string> InvalidEmailAddresses = new List<string>();
foreach (string Recipient in recipients)
{
if (!(new EmailAddressAttribute().IsValid(Recipient)) && !InvalidEmailAddresses.Contains(Recipient))
{
InvalidEmailAddresses.Add(Recipient);
}
}
MethodResult = InvalidEmailAddresses;
}
catch//(Exception ex)
{
//ex.HandleException();
}
return MethodResult;
}
...以及演示它们的代码:
List<string> Recipients = GetRecipients();
bool IsValidEmailAddresses = IsValidEmailAddresses(Recipients);
if (IsValidEmailAddresses)
{
//Emails are valid. Your code here
}
else
{
StringBuilder sb = new StringBuilder();
sb.Append("The following addresses are invalid:");
List<string> InvalidEmails = GetInvalidEmailAddresses(Recipients);
foreach (string InvalidEmail in InvalidEmails)
{
sb.Append("\n" + InvalidEmail);
}
MessageBox.Show(sb.ToString());
}
另外,这个例子:
扩展超出规范,因为一个字符串用于包含0,一个或多个由分号分隔的电子邮件地址; 清楚地演示了如何使用EmailAddressAttribute对象的IsValid方法。
对于.Net 4.5以下版本的用户,可以选择
对于.Net 4.5不可用的情况,我使用以下解决方案:
具体来说,我使用:
public static bool IsValidEmailAddress(string emailAddress)
{
bool MethodResult = false;
try
{
MailAddress m = new MailAddress(emailAddress);
MethodResult = m.Address == emailAddress;
}
catch //(Exception ex)
{
//ex.HandleException();
}
return MethodResult;
}
public static List<string> GetInvalidEmailAddresses(List<string> recipients)
{
List<string> MethodResult = null;
try
{
List<string> InvalidEmailAddresses = new List<string>();
foreach (string Recipient in recipients)
{
if (!IsValidEmail(Recipient) && !InvalidEmailAddresses.Contains(Recipient))
{
InvalidEmailAddresses.Add(Recipient);
}
}
MethodResult = InvalidEmailAddresses;
}
catch //(Exception ex)
{
//ex.HandleException();
}
return MethodResult;
}
通过system . text . regulareexpressions检查电子邮件字符串的格式是否正确:
public static bool IsValidEmailId(string InputEmail)
{
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(InputEmail);
if (match.Success)
return true;
else
return false;
}
protected void Email_TextChanged(object sender, EventArgs e)
{
String UserEmail = Email.Text;
if (IsValidEmailId(UserEmail))
{
Label4.Text = "This email is correct formate";
}
else
{
Label4.Text = "This email isn't correct formate";
}
}
There are a lot of strong answers here. However, I recommend that we take a step back. @Cogwheel answers the question https://stackoverflow.com/a/1374644/388267. Nevertheless, it could be costly in a bulk validation scenario, if many of the email address being validated are invalid. I suggest that we employ a bit of logic before we enter into his try-catch block. I know that the following code could be written using RegEx but that could be costly for new developers to understand. This is my twopence worth:
public static bool IsEmail(this string input)
{
if (string.IsNullOrWhiteSpace(input)) return false;
// MUST CONTAIN ONE AND ONLY ONE @
var atCount = input.Count(c => c == '@');
if (atCount != 1) return false;
// MUST CONTAIN PERIOD
if (!input.Contains(".")) return false;
// @ MUST OCCUR BEFORE LAST PERIOD
var indexOfAt = input.IndexOf("@", StringComparison.Ordinal);
var lastIndexOfPeriod = input.LastIndexOf(".", StringComparison.Ordinal);
var atBeforeLastPeriod = lastIndexOfPeriod > indexOfAt;
if (!atBeforeLastPeriod) return false;
// CODE FROM COGWHEEL'S ANSWER: https://stackoverflow.com/a/1374644/388267
try
{
var addr = new System.Net.Mail.MailAddress(input);
return addr.Address == input;
}
catch
{
return false;
}
}
这可能是对文本框进行电子邮件验证的最佳方式。
string pattern = null;
pattern = "^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
if (Regex.IsMatch("txtemail.Text", pattern))
{
MessageBox.Show ("Valid Email address ");
}
else
{
MessageBox.Show("Invalid Email Email");
}
只要在任何你想要的函数中包含。