An important step in preventing program bugs is catching erroneous data entry. One way to do this is to validate user-entered data after it is entered. An even better way is to prevent users from entering invalid data in the first place. For example, a TextBox in VB6 may be intended for the entry of numerical values only. Here's how to filter the input so it ignores letters and other inappropriate characters.
A number can contain any of the digits 0 through 9, a leading minus sign, and one and only one decimal point. We can check the key that was pressed in the control's KeyPress event procedure and let it through only if it meets one of the following criteria:
- It is a digit 0-9.
- It is a decimal point (period), and there is not already a decimal point in the text.
- It is a minus sign (hyphen) and both of the following are true: a) There is not already a minus sign in the text; b) The insertion point is at the beginning of the text.
The function in Listing A does the trick. It is passed a reference to the TextBox and the code of the key that was pressed. If one of the criteria above is met, the function returns the same key code. If not, 0 is returned with the result that the keystroke is ignored.
To use the function, call if from a TextBox'sKeyPress event, like this:
Private Sub Text1_KeyPress(KeyAscii As Integer)
KeyAscii = NumericCharsOnly(Text1, KeyAscii)
You can use similar techniques to provide other kinds of input filtering for a TextBox.
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!