验证字符串是否是有效的电子邮件地址的最优雅的代码是什么?
当前回答
我是来偷电子邮件的验证码的。然后我发现答案中的代码不必要地扩展了。我相信我用最短的方式写出了最好的解决方案:
public static bool IsEmail(string email)
{
try
{
return new System.Net.Mail.MailAddress(email).Address == email && !email.Trim().EndsWith(".");
}
catch
{
return false;
}
}
其他回答
我将Poyson 1的答案简化如下:
public static bool IsValidEmailAddress(string candidateEmailAddr)
{
string regexExpresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
return (Regex.IsMatch(candidateEmailAddr, regexExpresion)) &&
(Regex.Replace(candidateEmailAddr, regexExpresion, string.Empty).Length == 0);
}
我写了一个函数来检查电子邮件是否有效。在大多数情况下,这似乎对我很有效。
结果:
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;
}
如果你正在使用FluentValidation,你可以写一些像这样简单的东西:
public cass User
{
public string Email { get; set; }
}
public class UserValidator : AbstractValidator<User>
{
public UserValidator()
{
RuleFor(x => x.Email).EmailAddress().WithMessage("The text entered is not a valid email address.");
}
}
// Validates an user.
var validationResult = new UserValidator().Validate(new User { Email = "açflkdj" });
// This will return false, since the user email is not valid.
bool userIsValid = validationResult.IsValid;
对@齿轮回答做了一点修改
public static bool IsValidEmail(this string email)
{
// skip the exception & return early if possible
if (email.IndexOf("@") <= 0) return false;
try
{
var address = new MailAddress(email);
return address.Address == email;
}
catch
{
return false;
}
}
/使用内部Regex在.Net4.5 >>>中创建“new EmailAddressAttribute();”组件,使用System.ComponentModel.DataAnnotations; //验证邮箱地址......测试和工作。
public bool IsEmail(string email)
{
if (String.IsNullOrEmpty(email))
{ return false; }
try
{
Regex _regex = new Regex("^((([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\\u" +
"FDF0-\\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-\\uFF" +
"EF])))\\.?$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled);
return _regex.IsMatch(email);
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
你也可以用这个:
http://msdn.microsoft.com/en-us/library/01escwtf (v = vs.110) . aspx
推荐文章
- 在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)
- 完全外部连接