验证字符串是否是有效的电子邮件地址的最优雅的代码是什么?
当前回答
以前,我写了一个EmailAddressValidationAttribute,它应该正确地验证表单中几乎任何相对正常的电子邮件地址
local-part@domain
它是System.ComponentModel.DataAnnotations。ValidationAttribute,所以使用非常简单。
而且,由于挖掘所有rfc和勘误表,并组装所需的所有位来正确枚举所有规则……太乏味了!-我在回答c#电子邮件地址验证源代码的问题时发布了验证器的源代码。
我的验证器无论怎么想象都不是完美的,只是对于初学者来说,它没有任何内置的对发出客户端javascript验证的支持,尽管将其添加进来并不太难。从我上面的回答来看:
Here's the validation attribute I wrote. It validates pretty much every "raw" email address, that is those of the form local-part@domain. It doesn't support any of the other, more...creative constructs that the RFCs allow (this list is not comprehensive by any means): comments (e.g., jsmith@whizbang.com (work)) quoted strings (escaped text, to allow characters not allowed in an atom) domain literals (e.g. foo@[123.45.67.012]) bang-paths (aka source routing) angle addresses (e.g. John Smith <jsmith@whizbang.com>) folding whitespace double-byte characters in either local-part or domain (7-bit ASCII only). etc. It should accept almost any email address that can be expressed thusly foo.bar@bazbat.com without requiring the use of quotes ("), angle brackets ('<>') or square brackets ([]). No attempt is made to validate that the rightmost dns label in the domain is a valid TLD (top-level domain). That is because the list of TLDs is far larger now than the "big 6" (.com, .edu, .gov, .mil, .net, .org) plus 2-letter ISO country codes. ICANN actually updates the TLD list daily, though I suspect that the list doesn't actually change daily. Further, [ICANN just approved a big expansion of the generic TLD namespace][2]). And some email addresses don't have what you'd recognize as a TLD (did you know that postmaster@. is theoretically valid and mailable? Mail to that address should get delivered to the postmaster of the DNS root zone.) Extending the regular expression to support domain literals shouldn't be too difficult.
其他回答
/// <summary>
/// Validates the email if it follows the valid email format
/// </summary>
/// <param name="emailAddress"></param>
/// <returns></returns>
public static bool EmailIsValid(string emailAddress)
{
//if string is not null and empty then check for email follow the format
return string.IsNullOrEmpty(emailAddress)?false : new Regex(@"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$", RegexOptions.IgnoreCase).IsMatch(emailAddress);
}
.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])))\.?$";
这是你问题的答案,供你核对。
using System;
using System.Globalization;
using System.Text.RegularExpressions;
public class RegexUtilities
{
public bool IsValidEmail(string strIn)
{
if (String.IsNullOrEmpty(strIn))
{
return false;
}
// Use IdnMapping class to convert Unicode domain names.
try
{
strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200));
}
catch (RegexMatchTimeoutException)
{
return false;
}
if (invalid)
{
return false;
}
// Return true if strIn is in valid e-mail format.
try
{
return Regex.IsMatch(strIn, @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))| [-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
private string DomainMapper(Match match)
{
// IdnMapping class with default property values.
IdnMapping idn = new IdnMapping();
string domainName = match.Groups[2].Value;
try
{
domainName = idn.GetAscii(domainName);
}
catch (ArgumentException)
{
invalid = true;
}
return match.Groups[1].Value + domainName;
}
}
这可能是对文本框进行电子邮件验证的最佳方式。
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");
}
只要在任何你想要的函数中包含。
一个简单的没有使用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地址等。
推荐文章
- 在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)
- 完全外部连接