使用 C# 使用正则表达式验证文本框并更改文本框背景颜色
Using C# to validate a TextBox using Regex and changing Texbox back color
我正在使用 winForms
来验证使用 regex
的名字。我的表单中有一个 textbox
和一个 button
。当您单击 button
时,程序会检查用户输入的名字是否有效。如果用户键入了无效的名字,textbox
将更改其颜色。我有一个方法,如果用户输入有效的名字,文本框将更改为其原始颜色 'white'
例如:
有效的名字:Z
名字无效:1
我遇到的问题是我的程序无法立即识别验证。 (eng。如果我输入字母 Z,文本框仍将是红色。)直到我按下另一个键,如 "space bar"、"backspace"、字母 "H" 或让我的程序意识到字母 Z 是有效名字的其他任何东西。
这是怎么回事?下图中的 Z 应该是有效的,但正如我之前所说,我必须输入另一个键才能让我的程序识别名字是有效的。
//checks if Regex code is wrong if so change the textbox color
public void Error_Checker()
{
if (First_Name_Regex.FNameRegx.IsMatch(textBox1.Text) == false)//First Name Validation
{
textBox1.BackColor = Color.Red;
}
}
//if the RegexCode is comes out true change color
private void textbox_White(object sender, KeyPressEventArgs e)
{
if (First_Name_Regex.FNameRegx.IsMatch(textBox1.Text))//First Name Validation
{
textBox1.BackColor = Color.White;
}
}
//textBox1 first name Regex validator
public static class First_Name_Regex
{
public static readonly Regex FNameRegx = new Regex("^[a-zA-Z]+$");
}
private void button1_Click(object sender, EventArgs e)
{
Error_Checker();
}
应该是这样的:
if ( (new Regex(@"^[A-Za-z]+$")).IsMatch(textBox1.Text) )
{
textBox1.ForeColor = Color.Black;
}
else
{
textBox1.ForeColor = Color.Red;
}
它应该在 TextChanged
事件中
我正在使用 winForms
来验证使用 regex
的名字。我的表单中有一个 textbox
和一个 button
。当您单击 button
时,程序会检查用户输入的名字是否有效。如果用户键入了无效的名字,textbox
将更改其颜色。我有一个方法,如果用户输入有效的名字,文本框将更改为其原始颜色 'white'
例如:
有效的名字:Z
名字无效:1
我遇到的问题是我的程序无法立即识别验证。 (eng。如果我输入字母 Z,文本框仍将是红色。)直到我按下另一个键,如 "space bar"、"backspace"、字母 "H" 或让我的程序意识到字母 Z 是有效名字的其他任何东西。
这是怎么回事?下图中的 Z 应该是有效的,但正如我之前所说,我必须输入另一个键才能让我的程序识别名字是有效的。
//checks if Regex code is wrong if so change the textbox color
public void Error_Checker()
{
if (First_Name_Regex.FNameRegx.IsMatch(textBox1.Text) == false)//First Name Validation
{
textBox1.BackColor = Color.Red;
}
}
//if the RegexCode is comes out true change color
private void textbox_White(object sender, KeyPressEventArgs e)
{
if (First_Name_Regex.FNameRegx.IsMatch(textBox1.Text))//First Name Validation
{
textBox1.BackColor = Color.White;
}
}
//textBox1 first name Regex validator
public static class First_Name_Regex
{
public static readonly Regex FNameRegx = new Regex("^[a-zA-Z]+$");
}
private void button1_Click(object sender, EventArgs e)
{
Error_Checker();
}
应该是这样的:
if ( (new Regex(@"^[A-Za-z]+$")).IsMatch(textBox1.Text) )
{
textBox1.ForeColor = Color.Black;
}
else
{
textBox1.ForeColor = Color.Red;
}
它应该在 TextChanged
事件中