Putting Textbox Validation in a function

thugster69

Active member
Joined
Jun 17, 2010
Messages
35
Programming Experience
Beginner
Is there any possibility that I can put this large chunk of code to a function so that I can call and verify the input without having to repeat the code for every textbox.keyPress event.

Here it is:

VB.NET:
    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        With e
            If IsNumeric(.KeyChar) Or .KeyChar = "[" Or .KeyChar = "]" Or .KeyChar = ";" Or .KeyChar = ":" _
                 Or .KeyChar = "'" Or .KeyChar = "<" Or .KeyChar = "," Or .KeyChar = ">" Or .KeyChar = "\" _
                 Or .KeyChar = "|" Or .KeyChar = "." Or .KeyChar = "?" Or .KeyChar = "/" Or .KeyChar = "-" _
                 Or .KeyChar = "_" Or .KeyChar = "+" Or .KeyChar = "=" Or .KeyChar = "!" Or .KeyChar = "@" _
                 Or .KeyChar = "#" Or .KeyChar = "$" Or .KeyChar = "%" Or .KeyChar = "^" Or .KeyChar = "&" _
                 Or .KeyChar = "*" Or .KeyChar = "(" Or .KeyChar = ")" Or .KeyChar = "{" Or .KeyChar = "}" Then
                e.Handled = True
            End If
        End With
        
    End Sub
 
You can handle the event for multiple objects:
VB.NET:
... Handles OneTextBox.KeyPress, AnotherTextBox.KeyPress
Or add multiple handlers dynamically with AddHandler statement.

Of course you can also use a function method:
VB.NET:
Private Function ValidateChar(keychar As Char) As Boolean
The contents of this function can be simplified:
VB.NET:
Return "0123456789[];:'<,>\|.?/-_+=!@#$%^&*(){}".Contains(keychar)
Let me also introduce you to the Select Case statement where for each Case multiple matches can be listed:
VB.NET:
Select Case keychar
    Case "0"c, "1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c, "["c, "]"c, ";"c, _
         ":"c, "'"c, "<"c, ","c, ">"c, "\"c, "|"c, "."c, "?"c, "/"c, "-"c, "_"c, "+"c, _
         "="c, "!"c, "@"c, "#"c, "$"c, "%"c, "^"c, "&"c, "*"c, "("c, ")"c, "{"c, "}"c
        Return True
End Select
Here you would only check the keychar argument, in event handler you could do this:
VB.NET:
e.Handled = ValidateChar(e.KeyChar)
 
@John

Thanks for the code, I soon have to try that!

what does this line mean?:

VB.NET:
e.Handled = ValidateChar(e.KeyChar)

I thought the only equivalent value of e.handled is either TRUE or FALSE?

Thanks btw mate!
 
Handled property type is Boolean, and ValidateChar function returns a Boolean value.
 
Back
Top