验证字符串是否是有效的电子邮件地址的最优雅的代码是什么?
当前回答
这是我的答案——Phil的解决方案不适用于“someone@q.com”这样的单字母域名。信不信由你,这是used =)(例如,转到centurylink)。
菲尔的答案也只适用于PCRE标准…所以c#将会接受它,但javascript将会爆炸。这对于javascript来说太复杂了。所以你不能使用Phil的mvc验证属性的解决方案。
这是正则表达式。它将很好地与MVC验证属性一起工作。 @之前的所有内容都被简化了,这样至少javascript可以工作。我可以在这里放松验证,只要交换服务器不给我5.1.3。 @后面的都是Phil针对单字母域修改的解决方案。
public const string EmailPattern =
@"^\s*[\w\-\+_']+(\.[\w\-\+_']+)*\@[A-Za-z0-9]([\w\.-]*[A-Za-z0-9])?\.[A-Za-z][A-Za-z\.]*[A-Za-z]$";
对于那些建议使用system.net.mailmessage()的人来说,这个东西太灵活了。当然,c#将接受电子邮件,但交换服务器将爆炸5.1.3运行时错误一旦你试图发送电子邮件。
其他回答
通过system . text . regulareexpressions检查电子邮件字符串的格式是否正确:
public static bool IsValidEmailId(string InputEmail)
{
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(InputEmail);
if (match.Success)
return true;
else
return false;
}
protected void Email_TextChanged(object sender, EventArgs e)
{
String UserEmail = Email.Text;
if (IsValidEmailId(UserEmail))
{
Label4.Text = "This email is correct formate";
}
else
{
Label4.Text = "This email isn't correct formate";
}
}
我是来偷电子邮件的验证码的。然后我发现答案中的代码不必要地扩展了。我相信我用最短的方式写出了最好的解决方案:
public static bool IsEmail(string email)
{
try
{
return new System.Net.Mail.MailAddress(email).Address == email && !email.Trim().EndsWith(".");
}
catch
{
return false;
}
}
如果您将多个解决方案组合在一起来编写完美的代码呢?
我得到了排名最高的2个解决方案和评论,并结合起来得到更准确的答案。 它的短,快和可爱。
public static bool isValidEmail(string email)
{
try
{
var addr = new System.Net.Mail.MailAddress(email);
if (addr.Address == email)
{
string expression = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
if (Regex.IsMatch(email, expression))
{
if (Regex.Replace(email, expression, string.Empty).Length == 0)
return true;
}
return false;
}
return false;
}
catch
{
return false;
}
}
这可能是对文本框进行电子邮件验证的最佳方式。
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");
}
只要在任何你想要的函数中包含。
在“尝试块”发送一个验证电子邮件。 让用户打开电子邮件并单击一个链接,以验证电子邮件是真实的。
在此过程成功完成之前,该电子邮件被认为是无效的。
推荐文章
- c#中有任何连接字符串解析器吗?
- 在Linq中转换int到字符串到实体的问题
- 是否可以动态编译和执行c#代码片段?
- 创建自定义MSBuild任务时,如何从c#代码获取当前项目目录?
- c#和Java的主要区别是什么?
- 在c#中创建一个特定时区的DateTime
- .NET中的属性是什么?
- csproj文件中的“Service Include”是干什么用的?
- 如何使用try catch进行异常处理是最佳实践
- 替换字符串中第一次出现的模式
- .NET中字节的字面后缀?
- 如何处理AccessViolationException
- c#忽略证书错误?
- LINQ读取XML
- 如何强制LINQ Sum()返回0而源集合是空的