-
Oct 15th, 2014, 02:48 PM
#1
Thread Starter
Hyperactive Member
[RESOLVED] VB6 Input Validation to Disallow an All Alpha Character Field
Hello Everyone;
I'm a new vb6 programmer (I know I'm late to the game) who's developing an application that requires an input field (textbox) that only allows all numeric or alphanumeric content. But it must disallow fields that are character only. Right now this is what I have, but it doesn't disallow all character fields:
Code:
If KeyAscii = 13 Then '<= Pressed ENTER key
If strISBN = "" Then
MsgBox "Please key an ISBN or scan a bar code"
ElseIf Len(strISBN) < 10 Then
MsgBox "You entered too few characters"
Call modClearFrm1MainMenu.modClearFrm1MainMenu
ElseIf Len(strISBN) = 11 Or Len(strISBN) = 12 Then
MsgBox "You entered an invalid ISBN"
Call modClearFrm1MainMenu.modClearFrm1MainMenu
ElseIf Len(strISBN) > 13 Then
MsgBox "You entered too many characters"
Call modClearFrm1MainMenu.modClearFrm1MainMenu
Else
bValidISBN = True
End If
Else
If (KeyAscii <> 3 And KeyAscii <> 8 And KeyAscii <> 22) Then
If KeyAscii < 47 Or (KeyAscii > 57 And KeyAscii < 65) Then
MsgBox "You may only enter numbers and letters"
ElseIf (KeyAscii > 90 And KeyAscii < 97) Then
MsgBox "You may only enter numbers and letters"
ElseIf KeyAscii > 122 Then
MsgBox "You may only enter numbers and letters"
End If
End If
End If
If a user either keys or does a copy and paste of all alpha characters into my input field, the above code will not catch it. Can anyone offer any suggestions?
-
Oct 15th, 2014, 03:16 PM
#2
Re: VB6 Input Validation to Disallow an All Alpha Character Field
Without suggesting an immediate solution to your problem, let me suggest a change of direction.
If you were typing stuff & a typo generated one of those messages, or arrowing to another character & inserting/deleting generated one of those messages, I'd think you'd get a bit frustrated
At most, checking for alpha/numeric keystrokes is ok, but not the combinations, in my opinion. Do that after the user has finished entering data. This could be in the textbox LostFocus or Validate event.
-
Oct 15th, 2014, 03:38 PM
#3
Thread Starter
Hyperactive Member
Re: VB6 Input Validation to Disallow an All Alpha Character Field
Thank you for your response LaVolpe.
I understand what you're saying. But as a new vb6 programmer, I don't know how to invoke the textbox LostFocus or Validate events. As of now, the code I posted above is contained withing a KeyPress event:
Code:
Private Sub txtISBN_keypress(KeyAscii As Integer)
my code
End Sub
Validating the field for all alpha after the user is done typing makes sense, but can you suggest how I go about doing it?
-
Oct 15th, 2014, 05:13 PM
#4
Re: VB6 Input Validation to Disallow an All Alpha Character Field
This code will make a TextBox numeric only as well as prevent pasting alpha characters.
Additional validation can be added to LostFocus or Validate event.
Code:
Option Explicit
Private Const GWL_STYLE As Long = -16
Private Const ES_NUMBER As Long = &H2000
Private Declare Function GetWindowLong Lib "user32.dll" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32.dll" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Sub Form_Load()
Dim lStyle As Long
lStyle = GetWindowLong(Text1.hwnd, GWL_STYLE)
SetWindowLong Text1.hwnd, GWL_STYLE, lStyle Or ES_NUMBER
End Sub
-
Oct 15th, 2014, 05:33 PM
#5
Thread Starter
Hyperactive Member
Re: VB6 Input Validation to Disallow an All Alpha Character Field
I appreciate your response DrUnicode. But the field must accept numeric and alphanumeric. It must exclude input that consists of all alpha characters. I'm sorry if I wasn't clear in my previous posts.
-
Oct 15th, 2014, 05:37 PM
#6
Thread Starter
Hyperactive Member
Re: VB6 Input Validation to Disallow an All Alpha Character Field
LaVolpe your post makes a lot of sense to me. But being new to VB6 I don't know how to invoke the textbox LostFocus or Validate events. Can you point me in the right direction, and (hopefully) suggest some code that will accomplish what I need?
-
Oct 15th, 2014, 05:44 PM
#7
Re: VB6 Input Validation to Disallow an All Alpha Character Field
You don't invoke them, they occur automatically as long as the textbox had focus. The Validate event occurs when moving to another control that has the CausesValidation property set to true: default
In one of these events, loop thru each character of the textbox or use some other method to look for 'illegal' characters
Code:
' Ctrl+G to show the immediate window & see these printed out
Private Sub Text1_LostFocus()
Debug.Print "lost focus event"
End Sub
Private Sub Text1_Validate(Cancel As Boolean)
Debug.Print "validation event"
End Sub
-
Oct 15th, 2014, 06:32 PM
#8
Re: VB6 Input Validation to Disallow an All Alpha Character Field
The fine details are all up to you really.. I would use something like that as a start, in the keydown event of the text box.
Code:
Select Case keyascii
Case 13
Rem get the string and perform your validation for length and stuff
Rem check that there both digits and alpha
Rem warn the user if is something wrong.
Rem proceed if valid
Case 48 To 57, 65 To 90, 97 To 122 'others too if there are
Rem a valid character
rem no need to do anything
Case Else
Rem an unwanted character was entered
Rem don't annoy the user with a dialog box message
Rem take the string, remove the offending character yourself
Rem and replace back the string with only good characters
Rem you can beep him though
Beep
End Select
That goes for each character entered one a time. If the user does a copy and paste, a single Change event will be generated... perform your valid field routine there too.
Last edited by Navion; Oct 15th, 2014 at 06:38 PM.
-
Oct 15th, 2014, 07:29 PM
#9
Re: VB6 Input Validation to Disallow an All Alpha Character Field
Personally, never been a big fan of controlling keyboard input. No numbers, all numbers, maybe use of a mask edit box, ok maybe. Many times, not enough thought was put into it & arrow keys, backspace, home/end, and other keystrokes inadvertently get blocked which adds to frustration.
My m.o. is wait until a 'submit' button has been clicked & then validate the entire form, as needed
-
Oct 15th, 2014, 08:19 PM
#10
Re: VB6 Input Validation to Disallow an All Alpha Character Field
The following validation code is based on the ISBN Wikipedia article:
Code:
Private Sub Text1_KeyPress(KeyAscii As Integer)
Const PROMPT = "You may only enter numbers!" & vbNewLine & vbNewLine & _
"For ISBN-10, the letter X is also allowed as the last character."
Dim bValidISBN As Boolean, strISBN As String
If KeyAscii = vbKeyReturn Then
strISBN = Text1.Text
Select Case Len(strISBN)
Case 0&: MsgBox "Please enter an ISBN or scan a bar code!", vbExclamation
Case Is <= 9&: MsgBox "You have entered too few characters!", vbExclamation
modClearFrm1MainMenu.modClearFrm1MainMenu
Case 10&: bValidISBN = strISBN Like "#########[0-9Xx]"
If Not bValidISBN Then MsgBox PROMPT, vbExclamation
Case 11&, 12&: MsgBox "You have entered an invalid ISBN!", vbExclamation
modClearFrm1MainMenu.modClearFrm1MainMenu
Case 13&: bValidISBN = strISBN Like "#############"
If Not bValidISBN Then MsgBox PROMPT, vbExclamation
Case Is >= 14&: MsgBox "You have entered too many characters!", vbExclamation
modClearFrm1MainMenu.modClearFrm1MainMenu
End Select
End If
End Sub
On Local Error Resume Next: If Not Empty Is Nothing Then Do While Null: ReDim i(True To False) As Currency: Loop: Else Debug.Assert CCur(CLng(CInt(CBool(False Imp True Xor False Eqv True)))): Stop: On Local Error GoTo 0
Declare Sub CrashVB Lib "msvbvm60" (Optional DontPassMe As Any)
-
Oct 15th, 2014, 10:28 PM
#11
Thread Starter
Hyperactive Member
Re: VB6 Input Validation to Disallow an All Alpha Character Field
My apologies to everyone for not being as clear as I could have been when initially describing my problem. As time goes on I'll do better. I appreciate all of the responses I've received thus far. But we're still not zeroing in on a workable solution; primarily due to me not explaining the challenge well. So let me try again.
I'm pulling pricing and product data from the Amazon.com website API. The vehicle they use as a unique identifier is a field they call an "ASIN," which is a form of an ISBN on steroids. The Wikipedia that describes it is here:
https://en.wikipedia.org/wiki/Amazon...ication_Number
The ASIN is an alphanumeric field that can contain all numeric characters, or a mixture of letters and numbers, but it can't contain all alpha characters. Here are examples of valid values:
0983129606 <- A 10-digit ISBN that's all numeric
9780983129608 <- A 13-digit ISBN that's all numeric
034580404X <- A 10-digit alphanumeric ISBN with a trailing "X"
B0015DWLQ2 <- A 10-digit alphanumeric Amazon ASIN
B000O2R066 <- Another 10-digit alphanumeric Amazon ASIN with 3 zero's
My field, strISBN must accept all five possible data inputs. I really like LaVolpe's idea of validating the alphanumeric fields after all of the characters have been keyed and the user hits the enter key. And I think Bonnie West's sample code is very cool. Much clearer, compact, and elegant than the sample code I posted that I'm currently using. I especially liked the use of the Select Case statement. But Bonnie's solution doesn't address alphanumeric entries.
I'd like to use Bonnie's code but the alphanumeric formats need to be addressed. I've played around with the Like statement in Bonnie's code, but I just can't get it to work. Can anyone help? I feel dumb not being able to figure this out. Thanks a million!
Last edited by vb6coder14; Oct 15th, 2014 at 10:53 PM.
-
Oct 15th, 2014, 10:59 PM
#12
Re: VB6 Input Validation to Disallow an All Alpha Character Field
Be careful.
In a Windows user interface the "enter" key is used to select the Default control, typically a submit, update, etc. button. Just like the "escape" selects the Cancel control.
The "tab" and "shift-tab" keystrokes are used to navigate among controls.
If we're to assume lowercase is legal this works:
Code:
Private Sub Text1_Validate(Cancel As Boolean)
'Fail on non-alphanumeric:
Cancel = Text1.Text Like "*[!0-9A-Za-z]*"
If Not Cancel Then
'Fail if not at least one digit:
Cancel = Not Text1.Text Like "*[0-9]*"
End If
If Cancel Then Beep
End Sub
To disallow lowercase you might replace the Text by UCase$(Text) and remove the lowercase letters from the pattern.
-
Oct 15th, 2014, 11:02 PM
#13
Re: VB6 Input Validation to Disallow an All Alpha Character Field
I haven't read through the other code posted thus far but I am thinking assuming I understand the requirement that you need to scan whatever was entered for a numeric character once all the data is entered into the field either in the lost focus, validate or submit routine.
The simple way to make sure at least 1 numeric character is entered is to simply loop through the string and check each character to see if it is numeric, once any numeric character is found then you can exit the loop with a true result, else you reach the end of the loop and should be a false result.
If you also need to check the length and/or patterns then that is another matter that would require additional tests.
-
Oct 16th, 2014, 02:00 AM
#14
Thread Starter
Hyperactive Member
Re: VB6 Input Validation to Disallow an All Alpha Character Field
dilettante, your suggestion inspired me to come up with a solution to my problem that works well. Thank you very much! I simply added one more 'ElseIf' statement at the end of the 'if KeyAscii = 13' branch using the Like statement. Here's the code I came up with:
Code:
Option Explicit
Public Sub modValidateISBN(KeyAscii As Integer, strISBN As String, bValidISBN As Boolean)
On Error GoTo ErrorRoutine
bValidISBN = False
' Allow ENTER (13), CTRL-V (22), CTRL-C (3), BACKSPACE (8) and test everything else
If KeyAscii = 13 Then '<= Pressed ENTER key
If strISBN = "" Then
MsgBox "Please key an ISBN or scan a bar code"
ElseIf Len(strISBN) < 10 Then
MsgBox "You entered too few characters"
Call modClearFrm1MainMenu.modClearFrm1MainMenu
ElseIf Len(strISBN) = 11 Or Len(strISBN) = 12 Then
MsgBox "You entered an invalid ISBN"
Call modClearFrm1MainMenu.modClearFrm1MainMenu
ElseIf Len(strISBN) > 13 Then
MsgBox "You entered too many characters"
Call modClearFrm1MainMenu.modClearFrm1MainMenu
ElseIf strISBN Like "*[0-9]*" Then
bValidISBN = True
Else
bValidISBN = False
MsgBox "ISBN must be all numeric or a mix of letters and numbers"
Call modClearFrm1MainMenu.modClearFrm1MainMenu
End If
Else
If (KeyAscii <> 3 And KeyAscii <> 8 And KeyAscii <> 22) Then
If KeyAscii < 47 Or (KeyAscii > 57 And KeyAscii < 65) Then
MsgBox "You may only enter numbers and letters"
ElseIf (KeyAscii > 90 And KeyAscii < 97) Then
MsgBox "You may only enter numbers and letters"
ElseIf KeyAscii > 122 Then
MsgBox "You may only enter numbers and letters"
End If
End If
End If
Exit Sub
ErrorRoutine:
If Err.Number > 0 Then
Call gscErrRtn.gscErrRtn
End If
End Sub
It works reasonably well, but it still has problems. For instance, if a user keys an invalid character, a popup message appears, but the invalid character remains in the input box. It's up to the user to hit backspace and correct the error. It's only a minor problem though becasue if the user fails to do so, the Amazon lookup will simply result in a "Not Found" condition and the program will clear the input screen.
Not as elegant as I would like, but like I said, it works reasonably well. I still love the simplicity of Bonnie's code, but I just couldn't get the input mask to work. I tried modifying the following line of code but I kept getting a 'Type mismatch' error:
Code:
Case 10&: bValidISBN = strISBN Like "#########[0-9Xx]" Or bValidISBN = strISBN Like "[!A-Za-z]"
If anyone can help me make Bonnie's code work, or Bonnie, if you're still around, I would greatly appreciate the additional help.
Meanwhile, I still learned a great deal trying all of the different suggestions I got from the responses I received. That alone made this effort worthwhile!
Last edited by vb6coder14; Oct 16th, 2014 at 02:05 AM.
-
Oct 16th, 2014, 06:25 AM
#15
Re: VB6 Input Validation to Disallow an All Alpha Character Field
Originally Posted by vb6coder14
I tried modifying the following line of code but I kept getting a 'Type mismatch' error:
Code:
bValidISBN = strISBN Like "#########[0-9Xx]" Or bValidISBN = strISBN Like "[!A-Za-z]"
That's most likely because strISBN couldn't be coerced to a number (it probably contained alphabetic character(s)). In the above expression, the highlighted subexpression is evaluated first before either the Or or Like operators. Remember, the "=" character is used for both assignment and equality comparison. In that expression, you were testing whether the Boolean variable bValidISBN and the String variable strISBN were equal. Different data types can't be compared directly, so VB6 implicitly coerces one of them to the data type of the other (this is known as the Evil Type Coercion). In this situation, VB6 tried converting the string to a number (internally, Booleans are just Integers). Since the string probably contained an alphabetic character, it failed, hence the "Type mismatch" error. I recommend that you consult the Operator Precedence chart whenever you're constructing a relatively complex expression.
Originally Posted by vb6coder14
... but I just couldn't get the input mask to work.
Try this instead:
Code:
Case 10&: bValidISBN = strISBN Like "*#*" And _
strISBN Like "[0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z]"
On Local Error Resume Next: If Not Empty Is Nothing Then Do While Null: ReDim i(True To False) As Currency: Loop: Else Debug.Assert CCur(CLng(CInt(CBool(False Imp True Xor False Eqv True)))): Stop: On Local Error GoTo 0
Declare Sub CrashVB Lib "msvbvm60" (Optional DontPassMe As Any)
-
Oct 16th, 2014, 10:01 AM
#16
Thread Starter
Hyperactive Member
Re: VB6 Input Validation to Disallow an All Alpha Character Field
Bonnie;
Thank you once again so sharing so generously! Your solution works quite nicely. However, I did add a new Case statement that validates 12-digit UPC codes and I formatted it a bit for readability. Here's what my final code looks like:
Code:
If KeyAscii = vbKeyReturn Then '<= Pressed ENTER key
Select Case Len(strISBN)
Case 0&: MsgBox "Please enter an ISBN or scan a bar code!", vbExclamation
Case Is <= 9&: MsgBox "You have entered too few characters!", vbExclamation
modClearFrm1MainMenu.modClearFrm1MainMenu
Case 10&: bValidISBN = strISBN Like "*#*" And _
strISBN Like "[0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z][0-9A-Za-z]"
If Not bValidISBN Then
MsgBox "You may only enter all numbers or a combination of letters and numbers!" & vbNewLine & _
"No special characters are allowed.", vbExclamation
End If
Case 11&: MsgBox "You have entered an invalid ISBN!", vbExclamation
modClearFrm1MainMenu.modClearFrm1MainMenu
Case 12&: bValidISBN = strISBN Like "############"
If Not bValidISBN Then
MsgBox "UPC Codes must be all numeric!", vbExclamation
modClearFrm1MainMenu.modClearFrm1MainMenu
End If
Case 13&: bValidISBN = strISBN Like "#############"
If Not bValidISBN Then
MsgBox "13-digit ISBNs must be all numeric!", vbExclamation
End If
Case Is >= 14&: MsgBox "You have entered too many characters!", vbExclamation
modClearFrm1MainMenu.modClearFrm1MainMenu
End Select
End If
Also, thank you for the links about Evil Type Coercion and Operator Precedence. I found them both to be very informative and helpful.
I certainly hope others will read these posts and make use of this approach. I'm very happy with the result. How do I give you programming points?
Last edited by vb6coder14; Oct 16th, 2014 at 10:12 AM.
-
Oct 16th, 2014, 07:33 PM
#17
Re: VB6 Input Validation to Disallow an All Alpha Character Field
Originally Posted by vb6coder14
I'm very happy with the result.
Glad to hear that! Good luck with the rest of your project!
Oh, BTW, please don't forget to mark this thread Resolved! Thank you!
On Local Error Resume Next: If Not Empty Is Nothing Then Do While Null: ReDim i(True To False) As Currency: Loop: Else Debug.Assert CCur(CLng(CInt(CBool(False Imp True Xor False Eqv True)))): Stop: On Local Error GoTo 0
Declare Sub CrashVB Lib "msvbvm60" (Optional DontPassMe As Any)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|