how to validate a text box to accept only alphabets and numbers. no special characters. in vb.net

i have tried the following code but it doesn't allow numbers but it allows alphabets only

Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
        If (Microsoft.VisualBasic.Asc(e.KeyChar) < 65) _
            Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 90) _
            And (Microsoft.VisualBasic.Asc(e.KeyChar) < 97) _
            Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 122) Then
            'Allowed space
            If (Microsoft.VisualBasic.Asc(e.KeyChar) <> 32) Then
                e.Handled = True
            End If
        End If
        ' Allowed backspace
        If (Microsoft.VisualBasic.Asc(e.KeyChar) = 8) Then
            e.Handled = False
        End If
End Sub

Dani AI

Generated

your KeyPress logic only whitelists A–Z and a–z, so 0–9 will always be rejected. Mixing Or and And without grouping also makes the condition hard to reason about. As hints, keep it simple and explicitly allow only what you want.

Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox2.KeyPress
    Select Case e.KeyChar
        Case "0"c To "9"c, "A"c To "Z"c, "a"c To "z"c
            ' allowed
        Case ChrW(8) ' Backspace
            ' allowed
        Case Else
            e.Handled = True
    End Select
End Sub

Notes:

  • Add " "c to the allowed list if you want to permit spaces.
  • The code above restricts to ASCII letters/digits. If you need letters from other languages, switch to a regex-based check instead of ranges.

If this thread is about ASP.NET Web Forms (the tag suggests it might be), use a validator so paste and non-keyboard input are handled reliably. Client-side and server-side validation should match:

<asp:RegularExpressionValidator ID="revAlnum" runat="server"
    ControlToValidate="TextBox2"
    ValidationExpression="^[A-Za-z0-9]+$"
    ErrorMessage="Letters and digits only." Display="Dynamic" />

Regardless of WinForms or Web Forms, also validate the final value (e.g., in Validating, TextChanged, or on the server) to catch pasted text and IME input that KeyPress may not see.

Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If Char.IsLetterOrDigit(e.KeyChar) Then
            e.Handled = False
        Else
            e.Handled = True
        End If
 End Sub
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.