7 replies
by syscokid
What language? I'm sure most have an IsNumeric function or something similar. So
Dim MyVar, MyCheck
MyVar=ABC 'this is the value the user entered
MyCheck=IsNumeric(MyVar) 'is MyVar Numeric?
If MyCheck=False
Goto ErrorHandler
End If
and you'd take them out of the main program to an Erorhandler where you could return them a message box that numerics only are required.
by corbinj
by ann777
You haven't said which programming language you are using, but generally most (if not all), have an option for the type of field. Set that type of field to "numerical." That way only numerical values will be accepted.
Else set a check for input on that field <"999999" or whatever you have the maximum number of numerical input values. For instance if a valid input is 123 or 999 but not 1234 or 1000... then set an "IF x<1000 then goto ... else repeat the loop for a valid input" statement.
by corbinj
by sl-campbell
Both answers above will work but I prefer to use code like in answer #1. The additional touch to this would be to put the code in the Key_Press event (if you go to the code window and click on the left drop-down for the control in question, and thenin the right drop-down click on the Key_press event, you will see this event on your screen, or you can paste in the below code - you will only need to change the text box control name).
The advantage of this is that the key stroke will be capturedas the user enters it, and not when the user tries to move the focus to another control. The user will not even see the wrong key entered - nothing will happen. And the code can be easily used in other programs.
This will give you full control and you can further define the cases, such as if you want the user to also beable to enter a comma.
'START CODE BLOCK
Private Sub Text1_KeyPress(KeyAscii As Integer)
Const cPERIOD% = 46
Select Case KeyAscii
Case vbKeyBack, vbKeyClear 'Allow the BackSpace and Delete buttons
GoTo ExitEvent
Case cPERIOD
'Allow only one decimal
If InStr(Text1.Text, Chr$(cPERIOD)) Then KeyAscii = 0
GoTo ExitEvent
Case Else
'Only allow a true number
If Not IsNumeric(Chr$(KeyAscii)) Then
KeyAscii = 0
GoTo ErrHandler
End If
End Select
ExitEvent:
Exit Sub
ErrHandler:
'Add message box here if desired
GoTo ExitEvent
End Sub
'END CODE BLOCK
The next step would be to create a function in a module that does all of the above code.
Then have the function return the KeyAscii as an integer. You would then call in the Text box event it like this:
KeyAscii = fValNumberInput()
Or, put the code in a sub and pass the KeyAscii by reference:
ValNumberInput(KeyAscii)
by corbinj
by corbinj
This discussion is closed to new replies.
Trending Web Development posts
Sort by Trending