正则表达式为TextBox的textChanged事件

时间:2012-11-15 04:58:59

标签: c# .net regex winforms

在我的项目中,我TextBoxes内有很多TabControl,我给的是同样的事件:(工作

在我的表单构造函数中:

    SetProperty(this);

private void SetProperty(Control ctr)
{
    foreach (Control control in ctr.Controls)
    {
        if (control is TextBox)  
        {
            control.TextChanged += new EventHandler(ValidateText);
        }
        else
        {
           if (control.HasChildren) 
           {
               SetProperty(control);  //Recursive function if the control is nested
           }
        }
    }
}

现在我正在尝试将TextChanged事件提供给所有TextBox。像这样的东西:

    private void ValidateText(object sender,EventArgs e)
    {
        String strpattern = @"^[a-zA-Z][a-zA-Z0-9\'\' ']{1,20}$"; //Pattern is Ok
        Regex regex = new Regex(strpattern);  
        //What should I write here?             
    }

我不知道在上面的方法中要写什么,因为没有一个文本框需要考虑。请建议。

编辑:我提到的模式不应该被允许进入TextBox,即文本应该自动转换为匹配的字符串。 (应该禁止我在模式中提到的字符。)

2 个答案:

答案 0 :(得分:3)

您应首先获取调用TextBox的引用,然后您可以匹配正则表达式进行验证,以便做出您想要的任何决定。

private void ValidateText(object sender, EventArgs e)
{
    TextBox txtBox = sender as TextBox;
    String strpattern = @"^[a-zA-Z][a-zA-Z0-9\'\' ']{1,20}$"; //Pattern is Ok
    Regex regex = new Regex(strpattern);
    if (!regex.Match(txtBox.Text).Success)
    {
        // passed
    }
}

已添加,最好是挂钩Validating事件,您可以随时调用此事件,同时为所有TextBoxes执行验证。

private void SetProperty(Control ctr)
{
    foreach (Control control in ctr.Controls)
    {
        if (control is TextBox)
        {
            control.Validating += ValidateText;
        }
        else
        {
            if (control.HasChildren)
            {
                SetProperty(control);  //Recursive function if the control is nested
            }
        }
    }
}

private void ValidateText(object sender, CancelEventArgs e)
{
    TextBox txtBox = sender as TextBox;
    String strpattern = @"^[a-zA-Z][a-zA-Z0-9\'\' ']{1,20}$"; //Pattern is Ok
    Regex regex = new Regex(strpattern);
    //What should I write here?
    if (!regex.Match(txtBox.Text).Success)
    {
        e.Cancel = true;
    }
    e.Cancel = false;
}

要执行验证,请调用此方法:

bool isValid = !this.ValidateChildren(ValidationConstraints.Enabled);

参考文献:

  1. Extend the Textbox Control to Validate Against Regular Expressions
  2. Validation in Windows Forms

答案 1 :(得分:0)

你也可以发送文本框控件将this.textbox1发送到事件处理程序方法,并在事件处理程序中使用正则表达式检查该控件的输入文本。

相关问题