验证字符串是否是有效的电子邮件地址的最优雅的代码是什么?
当前回答
最优雅的方法是使用. 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;
}
其他回答
在“尝试块”发送一个验证电子邮件。 让用户打开电子邮件并单击一个链接,以验证电子邮件是真实的。
在此过程成功完成之前,该电子邮件被认为是无效的。
.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])))\.?$";
我是来偷电子邮件的验证码的。然后我发现答案中的代码不必要地扩展了。我相信我用最短的方式写出了最好的解决方案:
public static bool IsEmail(string email)
{
try
{
return new System.Net.Mail.MailAddress(email).Address == email && !email.Trim().EndsWith(".");
}
catch
{
return false;
}
}
我经常用这个来验证电子邮件,它就像一个魅力。这验证了电子邮件必须在@之前至少有一个字符,并且在“”之前至少有一个字符。
public static bool ValidateEmail(string value, bool required, int minLength, int maxLength)
{
value = value.Trim();
if (required == false && value == "") return true;
if (required && value == "") return false;
if (value.Length < minLength || value.Length > maxLength) return false;
//Email must have at least one character before an @, and at least one character before the .
int index = value.IndexOf('@');
if (index < 1 || value.LastIndexOf('.') < index + 2) return false;
return true;
}
我写了一个函数来检查电子邮件是否有效。在大多数情况下,这似乎对我很有效。
结果:
dasddas-@.com => FALSE
-asd@das.com => FALSE
as3d@dac.coas- => FALSE
dsq!a?@das.com => FALSE
_dasd@sd.com => FALSE
dad@sds => FALSE
asd-@asd.com => FALSE
dasd_-@jdas.com => FALSE
asd@dasd@asd.cm => FALSE
da23@das..com => FALSE
_dasd_das_@9.com => FALSE
d23d@da9.co9 => TRUE
dasd.dadas@dasd.com => TRUE
dda_das@das-dasd.com => TRUE
dasd-dasd@das.com.das => TRUE
代码:
private bool IsValidEmail(string email)
{
bool valid = false;
try
{
var addr = new System.Net.Mail.MailAddress(email);
valid = true;
}
catch
{
valid = false;
goto End_Func;
}
valid = false;
int pos_at = email.IndexOf('@');
char checker = Convert.ToChar(email.Substring(pos_at + 1, 1));
var chars = "qwertyuiopasdfghjklzxcvbnm0123456789";
foreach (char chr in chars)
{
if (checker == chr)
{
valid = true;
break;
}
}
if (valid == false)
{
goto End_Func;
}
int pos_dot = email.IndexOf('.', pos_at + 1);
if(pos_dot == -1)
{
valid = false;
goto End_Func;
}
valid = false;
try
{
checker = Convert.ToChar(email.Substring(pos_dot + 1, 1));
foreach (char chr in chars)
{
if (checker == chr)
{
valid = true;
break;
}
}
}
catch
{
valid = false;
goto End_Func;
}
Regex valid_checker = new Regex(@"^[a-zA-Z0-9_@.-]*$");
valid = valid_checker.IsMatch(email);
if (valid == false)
{
goto End_Func;
}
List<int> pos_list = new List<int> { };
int pos = 0;
while (email.IndexOf('_', pos) != -1)
{
pos_list.Add(email.IndexOf('_', pos));
pos = email.IndexOf('_', pos) + 1;
}
pos = 0;
while (email.IndexOf('.', pos) != -1)
{
pos_list.Add(email.IndexOf('.', pos));
pos = email.IndexOf('.', pos) + 1;
}
pos = 0;
while (email.IndexOf('-', pos) != -1)
{
pos_list.Add(email.IndexOf('-', pos));
pos = email.IndexOf('-', pos) + 1;
}
int sp_cnt = pos_list.Count();
pos_list.Sort();
for (int i = 0; i < sp_cnt - 1; i++)
{
if (pos_list[i] + 1 == pos_list[i + 1])
{
valid = false;
break;
}
if (pos_list[i]+1 == pos_at || pos_list[i]+1 == pos_dot)
{
valid = false;
break;
}
}
if(valid == false)
{
goto End_Func;
}
if (pos_list[sp_cnt - 1] == email.Length - 1 || pos_list[0] == 0)
{
valid = false;
}
End_Func:;
return valid;
}
推荐文章
- 在c#中从URI字符串获取文件名
- 检查SqlDataReader对象中的列名
- 如何将类标记为已弃用?
- c# 8支持。net框架吗?
- Linq-to-Entities Join vs GroupJoin
- 为什么字符串类型的默认值是null而不是空字符串?
- 在list中获取不同值的列表
- 组合框:向项目添加文本和值(无绑定源)
- 如何为ASP.net/C#应用程序配置文件值中的值添加&号
- 从System.Drawing.Bitmap中加载WPF BitmapImage
- 如何找出一个文件存在于c# / .NET?
- 为什么更快地检查字典是否包含键,而不是捕捉异常,以防它不?
- [DataContract]的命名空间
- string. isnullorempty (string) vs. string. isnullowhitespace (string)
- 完全外部连接