如何在C#中使用正则表达式验证手机号码文本框和电子邮件文本框?
我想首先在前端验证它们,这样数据库就不会收到任何无效的输入,甚至不会对其进行检查。
我正在使用Windows窗体。
发布于 2011-06-17 15:00:24
您可以使用System.Text.RegularExpression
我将为您提供一个电子邮件验证的示例
然后像这样声明一个正则表达式
Regex myRegularExpression = new
Regex(" \b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b");假设您的电子邮件文本框为txtEmail
然后写下,
if(myRegularExpression.isMatch(txtEmail.Text))
{
//valid e-mail
}更新
不是正则表达式的专家,
这是到Regular expression to validate e-mail的链接
您可以从提供的链接中找到有关regEx的更多详细信息。
发布于 2011-11-10 23:03:03
//for email validation
System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
if (txt_email.Text.Length > 0)
{
if (!rEMail.IsMatch(txt_email.Text))
{
MessageBox.Show("E-Mail expected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txt_email.SelectAll();
e.Cancel = true;
}
}
//for mobile validation
Regex re = new Regex("^9[0-9]{9}");
if (re.IsMatch(txt_mobile.Text.Trim()) == false || txt_mobile.Text.Length > 10)
{
MessageBox.Show("Invalid Indian Mobile Number !!");
txt_mobile.Focus();
}发布于 2011-06-17 15:02:32
此代码将检查电子邮件地址是否有效:
string inputText = textBox1.Text;
if (Regex.IsMatch(inputText,
@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"))
{
MessageBox.Show("yes");
}
else
{
MessageBox.Show("no");
}(来源:http://msdn.microsoft.com/en-us/library/01escwtf.aspx)
对于电话号码来说,答案就不那么简单了--答案取决于你在世界的什么地方,你是否想要允许国际号码,手机是如何编号的(例如,在美国,你不能仅从电话号码就知道它是不是手机号码)。在维基百科上查找“电话号码计划”以获取更多信息。
https://stackoverflow.com/questions/6382300
复制相似问题