使用正则表达式处理文本框输入验证

时间:2010-12-06 15:42:34

标签: .net regex textbox

我需要验证一些文本框输入。我想使用正则表达式。

问题:

  

我在哪里根据文本框输入测试我的正则表达式?

通过使用KeyPress事件,我只能访问文本框的旧文本。我无法访问包含新输入的文本。如何在新输入中包含文本框文本? 我可以做text = text + input,但忽略了这样一个事实:输入可能在文本的中间,而不是总是在结尾。有什么想法吗?


以下是函数的文本,以防它有用。

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

    Dim decimalRex As Regex = New Regex("^[0-9]*[.]{0,1}[0-9]*$")'checks for decimal'

    If decimalRex.IsMatch(sender.Text) Then'notice this only tests the text, not the input'
        e.Handled = False
    Else
        e.Handled = True
    End If
 End Sub

编辑:

我最终没有包括我需要的其中一项要求。我希望能够动态清理文本框的输入,并确保错误的输入永远不会出现在文本框中。
我接受了我的问题的最佳答案,即使这是我需要的。我需要的解决方案如下:

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    If IsNumeric(e.KeyChar) Then
        e.Handled = False
    ElseIf e.KeyChar = "." Then
        If InStr(sender.text, ".") > 0 Then
            e.Handled = True
        Else
            e.Handled = False
        End If
    ElseIf Asc(e.KeyChar) = 8 Then
        e.Handled = False
    Else
        e.Handled = True
    End If
End Sub

3 个答案:

答案 0 :(得分:1)

您需要在TextBox的EditValueChanged事件

中执行此操作

答案 1 :(得分:1)

您可以使用TextChanged事件并在那里验证您的文字(如果您没有使用类似于文字上的绑定之类的东西)。

答案 2 :(得分:1)

使用以下内容捕获每个键的不匹配字符,并且可以轻松修改此方法以执行您要求的操作...但请参阅下文。

Private Sub ONSTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
    If e.KeyChar = Microsoft.VisualBasic.Strings.ChrW(Keys.Back) Then
        Exit Sub
    End If

    If Not characterRegex.IsMatch(e.KeyChar.ToString()) Then
        e.Handled = True
    End If
End Sub

如果您正在尝试验证完整字符串,那么您确实应该使用Validating事件,并在那里执行完整字符串的正则表达式。

Private Sub ONSTextBox_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Me.Validating
    If Not validationRegex.IsMatch(Text) Then
        errorProvider.SetError(Me, "Error Message Here")
        e.Cancel = True ' Keeps them from changing to another control until error is corrected.
    End If
End Sub