【发布时间】:2017-10-15 17:13:28
【问题描述】:
我有这个功能可以正常工作,但是有没有更简单的方法可以使用邮件地址类完成验证检查,它会更合适吗?提前致谢。
TextBox tb = new TextBox();
tb.KeyDown += new KeyEventHandler(txtEmail_KeyDown);
string strRegex = @"^(?("")("".+?(?<!\\)""@)|(([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]))";
Regex re = new Regex(strRegex); // New regex Object created
// Run Checks after the enter is pressed.
if (e.KeyCode == (Keys.Enter))
{
// checks for is match, if empty and length
if (!re.IsMatch(txtEmail.Text) || (txtEmail.Text.Equals("")) || txtEmail.Text.Length > 100)
{
// display messagebox with error
MessageBox.Show("Email not correct format!!!! ");
}
else
{
MessageBox.Show("Email Format is correct");
}
}
}
【问题讨论】:
-
这取决于您使用的正则表达式,因为有很多情况需要检查您是否要使用正则表达式限制输入
-
使用 mailAddress 类会更有效吗?以及上面检查所有 tld 的示例正则表达式怎么样
标签: c# regex winforms mailaddress