📅  最后修改于: 2023-12-03 15:42:32.386000             🧑  作者: Mango
电子邮件地址验证是Web开发中常见的需求。本文将介绍如何用C#对电子邮件地址进行验证。
using System.Text.RegularExpressions;
public static bool IsValidEmail(string email)
{
if (string.IsNullOrWhiteSpace(email))
return false;
try
{
// Normalize the domain
email = Regex.Replace(email, @"(@)(.+)$", DomainMapper,
RegexOptions.None, TimeSpan.FromMilliseconds(200));
// Examines the domain part of the email and normalizes it.
static string DomainMapper(Match match)
{
// Use IdnMapping class to convert Unicode domain names.
var idn = new IdnMapping();
// Pull out and process domain name (throws ArgumentException on invalid)
var domainName = idn.GetAscii(match.Groups[2].Value);
return match.Groups[1].Value + domainName;
}
}
catch (RegexMatchTimeoutException e)
{
return false;
}
catch (ArgumentException e)
{
return false;
}
try
{
return Regex.IsMatch(email,
@"^[^@\s]+@[^@\s]+\.[^@\s]+$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
string email = "example@email.com";
if (IsValidEmail(email))
{
Console.WriteLine("Valid email");
}
else
{
Console.WriteLine("Invalid email");
}
上面的代码片段展示了如何在C#中验证电子邮件地址。通过引入 System.Text.RegularExpressions
命名空间,使用正则表达式进行验证。将给定的电子邮件地址规范化以进行更好的验证。如果正则表达式匹配成功,电子邮件地址将被视为有效。