在C#中使用正则表达式验证数据格式。
using System.Text.RegularExpressions;
//文本框不能为空
private void txt_CourseName_TextChanged(object sender, EventArgs e)
{
if ((new Regex(@"\S{1}")).IsMatch(((TextBox)sender).Text))
{
((TextBox)sender).BackColor = Color.White;
((TextBox)sender).ForeColor = Color.Black;
}
else
{
((TextBox)sender).BackColor = Color.Red;
((TextBox)sender).ForeColor = Color.White;
}
}
//为数字
private void txt_XF_TextChanged(object sender, EventArgs e)
{
if ((new Regex(@"^\d+(\.\d+)?$")).IsMatch(((TextBox)sender).Text))
{
((TextBox)sender).BackColor = Color.White;
((TextBox)sender).ForeColor = Color.Black;
}
else
{
((TextBox)sender).BackColor = Color.Red;
((TextBox)sender).ForeColor = Color.White;
}
}
//为数字或“数字+周”
private void txt_ZXS_TextChanged(object sender, EventArgs e)
{
if ((new Regex(@"^\d+$")).IsMatch(((TextBox)sender).Text) || (new Regex(@"^\d+(\.\d+)?周$")).IsMatch(((TextBox)sender).Text))
{
((TextBox)sender).BackColor = Color.White;
((TextBox)sender).ForeColor = Color.Black;
}
else
{
((TextBox)sender).BackColor = Color.Red;
((TextBox)sender).ForeColor = Color.White;
}
}