验证字符串是否是有效的电子邮件地址的最优雅的代码是什么?
当前回答
另一个正则表达式匹配答案:
/// <summary>
/// Validates the email input
/// </summary>
internal static bool ValidateEmail(string _emailAddress)
{
string _regexPattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
return (string.IsNullOrEmpty(_emailAddress) == false && System.Text.RegularExpressions.Regex.IsMatch(_emailAddress, _regexPattern))
? true
: false;
}
其他回答
这是一个老问题,但我在SO上找到的所有答案,包括最近的答案,都与这个问题类似。然而,在。net 4.5 / MVC 4中,你可以通过从System.ComponentModel中添加[EmailAddress]注释来向表单添加电子邮件地址验证。DataAnnotations,所以我想知道为什么我不能只使用。net的内置功能。
这似乎是可行的,而且在我看来是相当优雅的:
using System.ComponentModel.DataAnnotations;
class ValidateSomeEmails
{
static void Main(string[] args)
{
var email = new EmailAddressAttribute();
email.IsValid("someone@somewhere.com"); //true
email.IsValid("someone@somewhere.co.uk"); //true
email.IsValid("someone+tag@somewhere.net"); //true
email.IsValid("futureTLD@somewhere.fooo"); //true
email.IsValid("fdsa"); //false
email.IsValid("fdsa@"); //false
email.IsValid("fdsa@fdsa"); //false
email.IsValid("fdsa@fdsa."); //false
//one-liner
if (new EmailAddressAttribute().IsValid("someone@somewhere.com"))
return true;
}
}
通过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";
}
}
如果您将多个解决方案组合在一起来编写完美的代码呢?
我得到了排名最高的2个解决方案和评论,并结合起来得到更准确的答案。 它的短,快和可爱。
public static bool isValidEmail(string email)
{
try
{
var addr = new System.Net.Mail.MailAddress(email);
if (addr.Address == email)
{
string expression = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
if (Regex.IsMatch(email, expression))
{
if (Regex.Replace(email, expression, string.Empty).Length == 0)
return true;
}
return false;
}
return false;
}
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;
}
一个简单的没有使用Regex(我不喜欢它的可读性差):
bool IsValidEmail(string email)
{
string emailTrimed = email.Trim();
if (!string.IsNullOrEmpty(emailTrimed))
{
bool hasWhitespace = emailTrimed.Contains(" ");
int indexOfAtSign = emailTrimed.LastIndexOf('@');
if (indexOfAtSign > 0 && !hasWhitespace)
{
string afterAtSign = emailTrimed.Substring(indexOfAtSign + 1);
int indexOfDotAfterAtSign = afterAtSign.LastIndexOf('.');
if (indexOfDotAfterAtSign > 0 && afterAtSign.Substring(indexOfDotAfterAtSign).Length > 1)
return true;
}
}
return false;
}
例子:
IsValidEmail(“@b.com”) // false IsValidEmail(“a@.com”) // false IsValidEmail(“a@bcom”) // false IsValidEmail(“a.b@com”) // false IsValidEmail(“a@b.”) // false IsValidEmail(“a b@c.com”) // false IsValidEmail(“a@b c.com”) // false IsValidEmail(“a@b.com”) // true IsValidEmail(“a@b.c.com”) // true IsValidEmail(“a+b@c.com”) // true IsValidEmail(“a@123.45.67.89”) // true
它意味着简单,因此它不处理罕见的情况,如电子邮件的括号域包含空格(通常是允许的),电子邮件的IPv6地址等。