我是c#的新手,如果您看到基本错误,请道歉。我想验证一个电子邮件地址,我正在使用公共bool,尝试catch然后公开虚空。我想从我能够做的相关HTML中检索电子邮件文本,然后使用' MailAddress'验证它是有效的电子邮件。
问题在于它抛出异常:
throw new Exception("email within booking confirmation summary is not valid");
我认为我使用的代码不正确,但有人可以指导我在代码中需要做的事情,以确保我正确验证电子邮件,因为我相信我有一些我不需要的代码。以下是代码:
public static bool IsEmail(string emailToValidate)
{
if (string.IsNullOrEmpty(emailToValidate))
return true;
try
{
new MailAddress(emailToValidate);
return true;
}
catch (Exception ex)
{
return false;
}
}
public void CheckEmailDisplayed()
{
var email = _driver.FindElement(ConfirmationResponsiveElements.ViewEmail);
var emailText = email.Text;
if (IsEmail(emailText))
{
Console.WriteLine("email is valid");
}
else
{
throw new Exception("email within booking confirmation summary is not valid");
}
ViewEmail指向下面的HTML标记:
public static By ViewEmail => By.ClassName("confirmation-banner__text");
由于
答案 0 :(得分:0)
请尝试以下方法: -
bool IsValidEmail(string email)
{
try
{
return new System.Net.Mail.MailAddress(email).Address == email;
}
catch
{
return false;
}
}
OR
使用此单线方法 -
using System.ComponentModel.DataAnnotations;
public bool IsValidEmail(string source)
{
return new EmailAddressAttribute().IsValid(source);
}
OR
.net 4.5添加了ions.EmaSystem.ComponentModel.DataAnnotatilAddressAttribute
您可以浏览EmailAddressAttribute's source,这是它在内部使用的正则表达式:
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])))\.?$";
OR
public static bool emailIsValid(string email)
{
string expression = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
if (Regex.IsMatch(email, expression))
{
return Regex.Replace(email, expression, string.Empty).Length == 0;
}
else
{
return false;
}
}
希望它会对你有所帮助:)。