【发布时间】: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。