Harish Harish - 1 year ago 102
Vb.net Question

Text box validation

I am using many text boxes in a form.
How do i validate them,
In certain text boxes I have to use only text and in some I have to use only numbers.
Is using ASCII is a right method or is there any easier method to do this. If so please let me know the coding.

Answer Source

Wow, this can be a very broad topic...

For numeric textboxes, you should probably restrict input during KeyPress event:

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

    Dim allowedChars As String = "0123456789"

    If allowedChars.IndexOf(e.KeyChar) = -1 Then
        ' Invalid Character
        e.Handled = True
    End If

End Sub

NOTE: This code sample is assuming WinForms, different approach must be used for web...

Regardless of the plat form, you should look into the validation controls offered by the framework, and that will allow you to validate that there is indeed input, values are in a specified range, and also using regex write more complicated validation rules.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download