0

I want to validate textbox with keyPress event. It should allow alphabets and "(" and ")" I have written code for alphabet check but don't know how to check for "(" and ")".

     Private Sub txtBankName_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtBankName.KeyPress
    If Not (Asc(e.KeyChar) = 8) Then
        If Not ((Asc(e.KeyChar) >= 97 And Asc(e.KeyChar) <= 122) Or (Asc(e.KeyChar) >= 65 And Asc(e.KeyChar) <= 90) Or Asc(e.KeyChar) = 32) Then
            e.KeyChar = ChrW(0)
            e.Handled = True
        End If
    End If
End Sub
user3422209
  • 195
  • 3
  • 17

1 Answers1

1

This allows all Letters and "(" & ")". Refer to these two SO questions:
How can I validate a string to only allow alphanumeric characters in it?
Only allow specific characters in textbox

Private Sub txtBankName_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtBankName.KeyPress    
    If System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[^a-zA-Z0-9()\b]") Then
       e.Handled = True
    End If
End Sub
Paul Karam
  • 4,052
  • 8
  • 30
  • 53
Hexxed
  • 683
  • 1
  • 10
  • 28
  • @user3422209 I just converted my C# Code to VB.net. Its just a verbatim string literal. Try my updated code. Just removed "@". – Hexxed Feb 03 '17 at 07:44
  • Thank you so much.. but this accepts [ ] brackets too.. It shouldn't be accepted – user3422209 Feb 03 '17 at 09:34
  • @user3422209 There modified it. The string `"[^a-zA-Z0-9()\b]"` denotes the allowed strings to be typed. `\b` Allows backspace to delete characters. – Hexxed Feb 04 '17 at 00:16