Is there a way to limit the input into a textbox to only alphanumeric character(just letters and numbers). I've seen a function that lets them only put in numbers, but not one for limiting it to letters and numbers
Printable View
Is there a way to limit the input into a textbox to only alphanumeric character(just letters and numbers). I've seen a function that lets them only put in numbers, but not one for limiting it to letters and numbers
You mean something like this:
Code:Private Sub txtAlarm_KeyPress(KeyAscii As Integer)
'Prevents the user from pressing certain keys
'KeyAscii <> 8 means ==> 8 represent backspace
'(Key < "0" Or Key > "9") ==> only numbers are allow
'Only these characters are allow ==>
'(Key <> ":") And (Key <> "a") And (Key <> "p") And (Key <> "m")
Key = Chr$(KeyAscii)
If KeyAscii <> 8 And _
(Key < "0" Or Key > "9") And _
(Key <> ":") And (Key <> "a") And (Key <> "p") And (Key <> "m") Then
Beep
KeyAscii = 0
End If
End Sub
This function will make sure that a key pressed is a number or a letter. You can also pass it a length value so that none of the length of the text can't go over a certain value. Pass length 0 for no limit.
To use this you pass the KeyAscii value, the length, and the textbox.
[Edited by Iain17 on 04-28-2000 at 10:14 AM]Code:
Private Sub Text1_KeyPress(KeyAscii As Integer)
'infinite length
KeyAscii = validateNormalKeyPress (Keyascii, 0, Text1)
'length limited to 8
KeyAscii = validateNormalKeyPress (Keyascii, 8, Text1)
End Sub
Function validateNormalKeyPress(KeyAscii As Integer, iLength As Integer, txtBox As TextBox) As Integer
On Error GoTo validateKeyError
If KeyAscii <> 8 Then
'if the number of characters in the text box is
'greater than iLength, and none of the charcters
'are highlighted then set keyascii to 0
If iLength <> 0 Then
If (Len(txtBox.Text) >= iLength) And _
(txtBox.SelLength = 0) _
Then
KeyAscii = 0
End If
End If
'if the keypressed is not a number or a letter
'then set keyascii = 0
If (KeyAscii <= 47) Or (KeyAscii >= 58) Then
If (KeyAscii <= 64) Or (KeyAscii >= 91) Then
If (KeyAscii <= 96) Or (KeyAscii >= 123) Then
KeyAscii = 0
End If
End If
End If
End If
validateNormalKeyPress = KeyAscii
Exit Function
validateKeyError:
displayError "Error Validating Key Press :"
End Function
To prevent user from pasting nonalphanumeric chars from clipboard you should consider to put your code in the change event
Cheers Kedaman.;)
I never though of that, i have been doing validation for a lot of text boxes, but i noticed the other day that the user could still paste what-ever crap they so wanted in the text box.
The user can never be trusted!
? Couldn't you also subclass the TextBox and toss out any WM_PASTE messages? Just an idea that I haven't got around to trying out yet.