C# 正则表达式电子邮件验证
我用这个C# 正则表达式电子邮件验证,c#,regex,validation,C#,Regex,Validation,我用这个 @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$" regexp来验证电子邮件 ([\w\.\-]+)-这是一级域(许多字母和数字,还有点和连字符) ([\w\-]+)-这是用于二级域的 (\。(\w){2,3})+-这适用于其他级别域(从3到无穷大),其中包括一个点和2或3个文本 这个正则表达式怎么了 编辑:它不匹配“something@someth.ing“电子邮件TLD类邮件与此不匹配,还有一些其他长TLD。此外,您还可以使用验证电子邮件地址,
@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
regexp来验证电子邮件
([\w\.\-]+)
-这是一级域(许多字母和数字,还有点和连字符)([\w\-]+)
-这是用于二级域的(\。(\w){2,3})+
-这适用于其他级别域(从3到无穷大),其中包括一个点和2或3个文本这个正则表达式怎么了 编辑:它不匹配“something@someth.ing“电子邮件TLD类邮件与此不匹配,还有一些其他长TLD。此外,您还可以使用验证电子邮件地址,正如Microsoft在注释中所解释的: 而不是使用正则表达式来验证电子邮件地址, 您可以使用System.Net.Mail.MailAddress类。断定 无论电子邮件地址是否有效,请将电子邮件地址传递给 MailAddress.MailAddress(字符串)类构造函数 这为您省去了很多麻烦,因为您不必编写(或试图理解其他人的)正则表达式。试试这个:
public static bool IsValidEmailAddress(this string s)
{
var regex = new Regex(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
return regex.IsMatch(s);
}
我有一个用于检查我使用的电子邮件地址的表达式 因为上面没有一个像我的一样短或准确,我想我会把它贴在这里
@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*"
+ "@"
+ @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$";
有关更多信息,请在此处阅读:
此外,这将基于电子邮件语法检查RFC有效性,而不是检查电子邮件是否确实存在。测试电子邮件是否确实存在的唯一方法是发送和发送电子邮件,并让用户通过单击链接或输入令牌来验证他们是否收到了电子邮件
还有一些废弃域名,比如Mailinator.com等等。这无法验证电子邮件是否来自一次性域。我认为@([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+$”
应该可以工作。你需要像这样写
string email = txtemail.Text;
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
Response.Write(email + " is correct");
else
Response.Write(email + " is incorrect");
请注意,如果出现以下情况,此操作将失败:
@
符号后有一个子域.info
试试这个,它对我有用:
public bool IsValidEmailAddress(string s)
{
if (string.IsNullOrEmpty(s))
return false;
else
{
var regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
return regex.IsMatch(s) && !s.EndsWith(".");
}
}
这并不满足RFCs 5321和5322的所有要求,但它适用于以下定义
@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";
下面是代码
const String pattern =
@"^([0-9a-zA-Z]" + //Start with a digit or alphabetical
@"([\+\-_\.][0-9a-zA-Z]+)*" + // No continuous or ending +-_. chars in email
@")+" +
@"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";
var validEmails = new[] {
"ma@hostname.com",
"ma@hostname.comcom",
"MA@hostname.coMCom",
"m.a@hostname.co",
"m_a1a@hostname.com",
"ma-a@hostname.com",
"ma-a@hostname.com.edu",
"ma-a.aa@hostname.com.edu",
"ma.h.saraf.onemore@hostname.com.edu",
"ma12@hostname.com",
"12@hostname.com",
};
var invalidEmails = new[] {
"Abc.example.com", // No `@`
"A@b@c@example.com", // multiple `@`
"ma...ma@jjf.co", // continuous multiple dots in name
"ma@jjf.c", // only 1 char in extension
"ma@jjf..com", // continuous multiple dots in domain
"ma@@jjf.com", // continuous multiple `@`
"@majjf.com", // nothing before `@`
"ma.@jjf.com", // nothing after `.`
"ma_@jjf.com", // nothing after `_`
"ma_@jjf", // no domain extension
"ma_@jjf.", // nothing after `_` and .
"ma@jjf.", // nothing after `.`
};
foreach (var str in validEmails)
{
Console.WriteLine("{0} - {1} ", str, Regex.IsMatch(str, pattern));
}
foreach (var str in invalidEmails)
{
Console.WriteLine("{0} - {1} ", str, Regex.IsMatch(str, pattern));
}
我在MSDN上找到了很好的文档 如何:验证字符串是否为有效的电子邮件格式 (请检查此代码是否还支持对Internet域名使用非ASCII字符。) 有两种实现,分别适用于.Net 2.0/3.0和.Net 3.5及更高版本。
2.0/3.0版本是:
bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
Invalid: @majjf.com
Invalid: A@b@c@example.com
Invalid: Abc.example.com
Valid: j..s@proseware.com
Valid: j.@server1.proseware.com
Invalid: js*@proseware.com
Invalid: js@proseware..com
Valid: ma...ma@jjf.co
Valid: ma.@jjf.com
Invalid: ma@@jjf.com
Invalid: ma@jjf.
Invalid: ma@jjf..com
Invalid: ma@jjf.c
Invalid: ma_@jjf
Invalid: ma_@jjf.
Valid: ma_@jjf.com
Invalid: -------
Valid: 12@hostname.com
Valid: d.j@server1.proseware.com
Valid: david.jones@proseware.com
Valid: j.s@server1.proseware.com
Invalid: j@proseware.com9
Valid: j_9@[129.126.118.1]
Valid: jones@ms1.proseware.com
Invalid: js#internal@proseware.com
Invalid: js@proseware.com9
Invalid: js@proseware.com9
Valid: m.a@hostname.co
Valid: m_a1a@hostname.com
Valid: ma.h.saraf.onemore@hostname.com.edu
Valid: ma@hostname.com
Invalid: ma@hostname.comcom
Invalid: MA@hostname.coMCom
Valid: ma12@hostname.com
Valid: ma-a.aa@hostname.com.edu
Valid: ma-a@hostname.com
Valid: ma-a@hostname.com.edu
Valid: ma-a@1hostname.com
Valid: ma.a@1hostname.com
Valid: ma@1hostname.com
我对该方法的测试结果为:
bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
Invalid: @majjf.com
Invalid: A@b@c@example.com
Invalid: Abc.example.com
Valid: j..s@proseware.com
Valid: j.@server1.proseware.com
Invalid: js*@proseware.com
Invalid: js@proseware..com
Valid: ma...ma@jjf.co
Valid: ma.@jjf.com
Invalid: ma@@jjf.com
Invalid: ma@jjf.
Invalid: ma@jjf..com
Invalid: ma@jjf.c
Invalid: ma_@jjf
Invalid: ma_@jjf.
Valid: ma_@jjf.com
Invalid: -------
Valid: 12@hostname.com
Valid: d.j@server1.proseware.com
Valid: david.jones@proseware.com
Valid: j.s@server1.proseware.com
Invalid: j@proseware.com9
Valid: j_9@[129.126.118.1]
Valid: jones@ms1.proseware.com
Invalid: js#internal@proseware.com
Invalid: js@proseware.com9
Invalid: js@proseware.com9
Valid: m.a@hostname.co
Valid: m_a1a@hostname.com
Valid: ma.h.saraf.onemore@hostname.com.edu
Valid: ma@hostname.com
Invalid: ma@hostname.comcom
Invalid: MA@hostname.coMCom
Valid: ma12@hostname.com
Valid: ma-a.aa@hostname.com.edu
Valid: ma-a@hostname.com
Valid: ma-a@hostname.com.edu
Valid: ma-a@1hostname.com
Valid: ma.a@1hostname.com
Valid: ma@1hostname.com
此选项可防止其他人在评论中提到无效电子邮件:
Abc.@example.com
Abc..123@example.com
name@hotmail
toms.email.@gmail.com
test@-online.com
/// <summary>
/// Validates the string is an Email Address...
/// </summary>
/// <param name="emailAddress"></param>
/// <returns>bool</returns>
public static bool IsValidEmailAddress(this string emailAddress)
{
var valid = true;
var isnotblank = false;
var email = emailAddress.Trim();
if (email.Length > 0)
{
// Email Address Cannot start with period.
// Name portion must be at least one character
// In the Name, valid characters are: a-z 0-9 ! # _ % & ' " = ` { } ~ - + * ? ^ | / $
// Cannot have period immediately before @ sign.
// Cannot have two @ symbols
// In the domain, valid characters are: a-z 0-9 - .
// Domain cannot start with a period or dash
// Domain name must be 2 characters.. not more than 256 characters
// Domain cannot end with a period or dash.
// Domain must contain a period
isnotblank = true;
valid = Regex.IsMatch(email, Regex.EmailPattern, RegexOptions.IgnoreCase) &&
!email.StartsWith("-") &&
!email.StartsWith(".") &&
!email.EndsWith(".") &&
!email.Contains("..") &&
!email.Contains(".@") &&
!email.Contains("@.");
}
return (valid && isnotblank);
}
/// <summary>
/// Validates the string is an Email Address or a delimited string of email addresses...
/// </summary>
/// <param name="emailAddress"></param>
/// <returns>bool</returns>
public static bool IsValidEmailAddressDelimitedList(this string emailAddress, char delimiter = ';')
{
var valid = true;
var isnotblank = false;
string[] emails = emailAddress.Split(delimiter);
foreach (string e in emails)
{
var email = e.Trim();
if (email.Length > 0 && valid) // if valid == false, no reason to continue checking
{
isnotblank = true;
if (!email.IsValidEmailAddress())
{
valid = false;
}
}
}
return (valid && isnotblank);
}
public class Regex
{
/// <summary>
/// Set of Unicode Characters currently supported in the application for email, etc.
/// </summary>
public static readonly string UnicodeCharacters = "À-ÿ\p{L}\p{M}ÀàÂâÆæÇçÈèÉéÊêËëÎîÏïÔôŒœÙùÛûÜü«»€₣äÄöÖüÜß"; // German and French
/// <summary>
/// Set of Symbol Characters currently supported in the application for email, etc.
/// Needed if a client side validator is being used.
/// Not needed if validation is done server side.
/// The difference is due to subtle differences in Regex engines.
/// </summary>
public static readonly string SymbolCharacters = @"!#%&'""=`{}~\.\-\+\*\?\^\|\/\$";
/// <summary>
/// Regular Expression string pattern used to match an email address.
/// The following characters will be supported anywhere in the email address:
/// ÀàÂâÆæÇçÈèÉéÊêËëÎîÏïÔôŒœÙùÛûÜü«»€₣äÄöÖüÜß[a - z][A - Z][0 - 9] _
/// The following symbols will be supported in the first part of the email address(before the @ symbol):
/// !#%&'"=`{}~.-+*?^|\/$
/// Emails cannot start or end with periods,dashes or @.
/// Emails cannot have two @ symbols.
/// Emails must have an @ symbol followed later by a period.
/// Emails cannot have a period before or after the @ symbol.
/// </summary>
public static readonly string EmailPattern = String.Format(
@"^([\w{0}{2}])+@{1}[\w{0}]+([-.][\w{0}]+)*\.[\w{0}]+([-.][\w{0}]+)*$", // @"^[{0}\w]+([-+.'][{0}\w]+)*@[{0}\w]+([-.][{0}\w]+)*\.[{0}\w]+([-.][{0}\w]+)*$",
UnicodeCharacters,
"{1}",
SymbolCharacters
);
}
它还可以防止电子邮件带有双点:
hello..world@example..com
尝试使用尽可能多的无效电子邮件地址进行测试
using System.Text.RegularExpressions;
public static bool IsValidEmail(string email)
{
return Regex.IsMatch(email, @"\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}\z")
&& Regex.IsMatch(email, @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*");
}
看
我使用上述代码验证电子邮件地址。请尝试以下代码:
public bool VailidateEntriesForAccount()
{
if (!(txtMailId.Text.Trim() == string.Empty))
{
if (!IsEmail(txtMailId.Text))
{
Logger.Debug("Entered invalid Email ID's");
MessageBox.Show("Please enter valid Email Id's" );
txtMailId.Focus();
return false;
}
}
}
private bool IsEmail(string strEmail)
{
Regex validateEmail = new Regex("^[\\W]*([\\w+\\-.%]+@[\\w\\-.]+\\.[A-Za-z] {2,4}[\\W]*,{1}[\\W]*)*([\\w+\\-.%]+@[\\w\\-.]+\\.[A-Za-z]{2,4})[\\W]*$");
return validateEmail.IsMatch(strEmail);
}
using System.Text.RegularExpressions;
if (!Regex.IsMatch(txtEmail.Text, @"^[a-z,A-Z]{1,10}((-|.)\w+)*@\w+.\w{3}$"))
MessageBox.Show("Not valid email.");
创建一个电子邮件验证器已经做了很多尝试,该验证器几乎可以满足全球对电子邮件的所有要求 您可以使用以下方法调用扩展方法:
myEmailString.IsValidEmailAddress();
您可以通过调用以下命令获得正则表达式模式字符串:
var myPattern = Regex.EmailPattern;
代码(主要是注释):
//
///验证字符串是否为电子邮件地址。。。
///
///
///布尔
公共静态bool IsValidEmailAddress(此字符串emailAddress)
{
var valid=true;
var isnotblank=false;
var email=emailAddress.Trim();
如果(email.Length>0)
{
//电子邮件地址不能以句点开头。
//名称部分必须至少包含一个字符
//在名称中,有效字符为:a-z 0-9!##&'=`{}~-+*?^|/$
//不能在@sign之前有句点。
//不能有两个@符号
//在域中,有效字符为:a-z 0-9-。
//域不能以句点或破折号开头
//域名必须为2个字符..不超过256个字符
//域不能以句点或破折号结束。
//域必须包含句点
isnotblank=true;
valid=Regex.IsMatch(email,Regex.EmailPattern,RegexOptions.IgnoreCase)&&
!email.StartsWith(“-”)&&
!email.StartsWith(“.”)&&
!email.EndsWith(“.”)和
!email.Contains(“…”)&&
!email.Contains(“.@”)&&
!email.Contains(“@”);
}
返回值(有效且不为空);
}
///
///验证字符串是否为电子邮件地址或电子邮件地址的分隔字符串。。。
///
///
///布尔
公共静态bool IsValidEmailAddressDelimitedList(此字符串为emailAddress,字符分隔符=';')
{
var valid=true;
var isnotblank=false;
字符串[]emails=emailAddress.Split(分隔符);
foreach(电子邮件中的字符串e)
{
var email=e.Trim();
if(email.Length>0&&valid)//if valid==false,没有理由继续检查
{
isnotblank=true;
如果(!email.IsValidEmailAddress())
{
有效=错误;
}
}
}
返回值(有效且不为空);
}
公共类正则表达式
{
///
///电子邮件等应用程序中当前支持的Unicode字符集。
///
公共静态只读字符串Unicode字符
///
///电子邮件等应用程序中当前支持的一组符号字符。
///如果正在使用客户端验证程序,则需要。
///如果验证在服务器端完成,则不需要。
///这种差异是由于正则表达式引擎的细微差异造成的。
///
公共静态只读字符串SymbolCharacters=@“!\\\%&'”=`{}~\.\-\+\*\?
string EmailPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
if (Regex.IsMatch(Email, EmailPattern, RegexOptions.IgnoreCase))
{
Console.WriteLine("Email: {0} is valid.", Email);
}
else
{
Console.WriteLine("Email: {0} is not valid.", Email);
}
string patternEmail = @"(?<email>\w+@\w+\.[a-z]{0,3})";
Regex regexEmail = new Regex(patternEmail);
public class LoginViewModel
{
[EmailAddress(ErrorMessage = "The email format is not valid")]
public string Email{ get; set; }
^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$
^(([^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$
public static bool IsValidEmail(string email)
{
var r = new Regex(@"^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");
return !String.IsNullOrEmpty(email) && r.IsMatch(email);
}
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);
^(?:[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+\\.)*[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!\\.)){0,61}[a-zA-Z0-9]?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\\[(?:(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\]))$
public static Regex EmailValidation()
{
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])))\.?$";
const RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture;
// Set explicit regex match timeout, sufficient enough for email parsing
// Unless the global REGEX_DEFAULT_MATCH_TIMEOUT is already set
TimeSpan matchTimeout = TimeSpan.FromSeconds(2);
try
{
if (AppDomain.CurrentDomain.GetData("REGEX_DEFAULT_MATCH_TIMEOUT") == null)
{
return new Regex(pattern, options, matchTimeout);
}
}
catch
{
// Fallback on error
}
// Legacy fallback (without explicit match timeout)
return new Regex(pattern, options);
}
public static class CommonExtensions
{
public static bool IsValidEmail(this string thisEmail)
=> !string.IsNullOrWhiteSpace(thisEmail) &&
new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$").IsMatch(thisEmail);
}
if (!emailAsString.IsValidEmail()) throw new Exception("Invalid Email");
using System.Text.RegularExpressions;
private bool EmailValidation(string pEmail)
{
return Regex.IsMatch(pEmail,
@"^(?("")("".+?(?<!\\)""@)|(([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));
}
const string atext = @"a-zA-Z\d!#\$%&'\*\+-/=\?\^_`\{\|\}~";
var localPart = $"[{atext}]+(\\.[{atext}]+)*";
var domain = $"[{atext}]+(\\.[{atext}]+)*";
Assert.That(() => EmailRegex = new Regex($"^{localPart}@{domain}$", Compiled),
Throws.Nothing);
public static bool isValidEmail(this string email)
{
string[] mail = email.Split(new string[] { "@" }, StringSplitOptions.None);
if (mail.Length != 2)
return false;
//check part before ...@
if (mail[0].Length < 1)
return false;
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\-\.]+$");
if (!regex.IsMatch(mail[0]))
return false;
//check part after @...
string[] domain = mail[1].Split(new string[] { "." }, StringSplitOptions.None);
if (domain.Length < 2)
return false;
regex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_\-]+$");
foreach (string d in domain)
{
if (!regex.IsMatch(d))
return false;
}
//get TLD
if (domain[domain.Length - 1].Length < 2)
return false;
return true;
}
bool IsValidEmail(string email)
{
return Regex.IsMatch(email, @"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))\z");
}
new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(input)
public static class FormValidationUtils
{
const string ValidEmailAddressPattern = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$";
public static bool IsEmailValid(string email)
{
var regex = new Regex(ValidEmailAddressPattern, RegexOptions.IgnoreCase);
return regex.IsMatch(email);
}
}
@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$",
string pattern = @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z";
//check first string
if (Regex.IsMatch(EmailId1 , pattern))
{
//if email is valid
Console.WriteLine(EmailId1+ " is a valid Email address ");
}
public bool IsEmailValid(string emailaddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}