Problem: How To Limit Edit Control Input to Numeric Only
Solution: There are times when you would like to limit allowed input into certain controls to numeric characters only (the digits 0..9, and ".", ",", and "-" characters, as well as the backspace). While this can be accomplished in several different ways (for example, the AfterChange event that gets fired when a control changes its value, or the OnValidate event which fires before the form's current data is saved to the linked table), this example takes the approach of filtering input chars as they are entered. This can be accomplished using a global script that can be called from multiple forms, and the OnKey event script on any given form.
In the OnKey event of the form, we can test whether the input is numeric or not. If not, then we can beep and discard the input. Let's say we only want to perform this numeric input validation:
dim AKey, VKey, MKey
GetLastKey(AKey, VKey, MKey)
if (AKey > 255) then Exit 'allow virtual keys to be processed by the OS
'if input to edNumeric control then check for numeric input only
if Forms().GetFocus = edNumeric.Index then
if not IsNumericInput(AKey) then
Beep(1)
Fail 'non-numeric entry disabled
endif
endif
As you can see, the OnKey script calls a global function named IsNumericInput and passes it the ASCII value of the character that was just received from the keyboard input queue. Let's create a Global function named IsNumericInput that examines that input char and returns True if it is a valid numeric char, or False if it is not. The backspace key is handled by the AKey = 8 test, which tests the ASCII code instead of testing the character as is done for the digits and numeric punctuation:
Function IsNumericInput(AKey)
dim char
char = CHR(AKey) 'get the character
if ((char >= "0") and (char <= "9")) _
or (char = ".") _
or (char = ",") _
or (char = "-") _
or (AKey = 8) then
IsNumericInput = true
else
IsNumericInput = false
endif
End Function
That should do it. You can then expand it to other controls and/or forms by adding additional IsNumericInput tests in the OnPenUp script.
Keywords: IsNumericInput, numeric, char, OnKey, GetLastKey, validate
KB ID: 10060
Updated: 2007-07-11
Satellite Forms KnowledgeBase Online