C# code to validate email address
验证字符串是否为有效的电子邮件地址的最优雅的代码是什么?
This is an old question, but all the answers I've found on SO, including more recent ones, are answered similarly to this one. However, in .Net 4.5 / MVC 4 you can add email address validation to a form by adding the [EmailAddress] annotation from System.ComponentModel.DataAnnotations, so I was wondering why I couldn't just use the built-in functionality from .Net in general.
This seems to work, and seems to me to be fairly elegant:
using System.ComponentModel.DataAnnotations;
class ValidateSomeEmails
{
static void Main(string[] args)
{
var foo = new EmailAddressAttribute();
bool bar;
bar = foo.IsValid("someone@somewhere.com"); //true
bar = foo.IsValid("someone@somewhere.co.uk"); //true
bar = foo.IsValid("someone+tag@somewhere.net"); //true
bar = foo.IsValid("futureTLD@somewhere.fooo"); //true
bar = foo.IsValid("fdsa"); //false
bar = foo.IsValid("fdsa@"); //false
bar = foo.IsValid("fdsa@fdsa"); //false
bar = foo.IsValid("fdsa@fdsa."); //false
//one-liner
if (new EmailAddressAttribute().IsValid("someone@somewhere.com"))
bar = true;
}
}
I took Phil's answer from #1 and created this class. Call it like this: bool isValid = Validator.EmailIsValid(emailString);
Here is the class:
using System.Text.RegularExpressions;
public static class Validator
{
static Regex ValidEmailRegex = CreateValidEmailRegex();
/// <summary>
/// Taken from http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx
/// </summary>
/// <returns></returns>
private static Regex CreateValidEmailRegex()
{
string validEmailPattern = @"^(?!.)(""([^""r]|[""r])*""|"
+ @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!.).)*)(?<!.)"
+ @"@[a-z0-9][w.-]*[a-z0-9].[a-z][a-z.]*[a-z]$";
return new Regex(validEmailPattern, RegexOptions.IgnoreCase);
}
internal static bool EmailIsValid(string emailAddress)
{
bool isValid = ValidEmailRegex.IsMatch(emailAddress);
return isValid;
}
}
链接地址: http://www.djcxy.com/p/2710.html
上一篇: 电子邮件地址允许使用哪些字符?
下一篇: 验证电子邮件地址的C#代码