I need to validate some textbox input. I want to use a regex.
The question:
Where do I test my regex against the textbox input?
By using the KeyPress event I can only access the old text of the textbox. I cant access the text with the new input included. How do I include the textbox text with the new input?
I could just do text = text + input, but that ignores the fact that the input could be in the middle of the text, not always at the end. Any ideas?
Below is the text of the function in case it is useful.
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
EDIT:
I ended up not including one of the requirements I needed. I wanted to be able to sanitize the input to the textbox on the fly, and making sure the bad input never appears in the textbox.
I accepted the best answer to my question, even though that is what I needed. The solution to what I needed is below:
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