Keypress Character Validation...Code Cleanup Help
I know that this is not the best way of doing this, so I am looking for suggestions for cleaning this up. Currently, it only allows the user to enter Alpha characters, spaces, and press the enter and backspace key in a textbox.
Code:
'allow alpha characters, spacebar and backspace key only
If (e.KeyChar < "A" OrElse e.KeyChar > "z") _
AndAlso e.KeyChar <> ControlChars.Back AndAlso Asc(e.KeyChar) <> Keys.Enter AndAlso Asc(e.KeyChar) <> Keys.Space Then
'Display error message
MessageBox.Show("Only alphabetic characters are allowed in this field.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
txtLastname.Focus()
e.Handled = True
End If
I need to write something to allow the following keys only:
Alpha keys, "Enter" key, "Backspace" key, "period" key, "ampersand", "spacebar" key, "apostrope" key, and "hypen" key
I want to make sure I am doing this with manage code. Thanks for any assistance.
-Jeremy
Re: Keypress Character Validation...Code Cleanup Help
you can use the Keys enum and convert them to a char for example
Code:
If e.KeyChar = Chr(Keys.Enter)
Re: Keypress Character Validation...Code Cleanup Help
I have modified my code as suggested, but this method does not appear to be working. Any ideas? Thanks
Code:
'allow alpha characters, spacebar and backspace key only
If (e.KeyChar < "A" OrElse e.KeyChar > "z") _
AndAlso e.KeyChar <> ControlChars.Back AndAlso e.KeyChar <> Chr(Keys.Enter) AndAlso e.KeyChar <> Chr(Keys.Space) _
AndAlso e.KeyChar <> Chr(Keys.Subtract) AndAlso e.KeyChar <> Chr(Keys.OemPeriod) AndAlso _
e.KeyChar <> Chr(Keys.CapsLock) AndAlso e.KeyChar <> Chr(Keys.ControlKey) AndAlso e.KeyChar <> Chr(Keys.ShiftKey) _
AndAlso e.KeyChar <> Chr(Keys.NumPad8) Then
'Display error message
MessageBox.Show("Only alphabetic characters are allowed in this field.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
txtLastname.Focus()
e.Handled = True
End If
Re: Keypress Character Validation...Code Cleanup Help
Code:
Private Sub aTextBox_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox1.KeyPress, TextBox2.KeyPress
'enter all valid characters here
Dim vldCHA As String = "ABCDEF-'"
'and the special ones here
Dim specCH() As Char = New Char() {Chr(Keys.Enter), Chr(Keys.Back)}
If vldCHA.IndexOf(e.KeyChar) <> -1 Then Exit Sub
If vldCHA.IndexOf(e.KeyChar.ToString.ToUpper) <> -1 Then Exit Sub
If Array.IndexOf(specCH, e.KeyChar) <> -1 Then Exit Sub
e.Handled = True 'bad character
End Sub