【问题标题】:Handling textbox input validation with a regex使用正则表达式处理文本框输入验证
【发布时间】:2010-12-07 02:36:56
【问题描述】:

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

问题:

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

通过使用 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

【问题讨论】:

  • 你应该使用RegularExpressionValidator。

标签: .net regex textbox


【解决方案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

【讨论】:

  • 被接受为我最初问题的最佳答案,但不是我需要的最佳答案。
【解决方案2】:

您需要在 TextBox 的 EditValueChanged 事件中执行此操作

【讨论】:

    【解决方案3】:

    您可以使用TextChanged 事件并在那里验证您的文本(如果您不使用更高级的东西,例如文本上的绑定)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      • 1970-01-01
      • 2011-03-10
      • 2019-01-07
      相关资源
      最近更新 更多