Wiki Home

Validating Data Entry

Namespace: VFP
You can provide data validation at the form / control level a couple different ways. This can be very important with applications in a distributed environment. Since distributed apps may be sending information over slow connections we should not send invalid data across the wire, only to have it bounce back.

Some examples of the available ways to perform data validation:
Say we have a Text Box control on a form called txtAge. This will allow the user to enter a person's age. The rules for txtAge are: Digits only.

Using Valid
The valid event fires just prior to the Lost Focus event. What the valid returns determines how the Focus changes.
For our example, add the following code to the valid event
local cStringToCheck

FOR nCharPos = 1 TO LEN( cStringToCheck  )
	IF NOT ISDIGIT( SUBSTR(cStringToCheck, nCharPos, 1))

When the user tries to move to another control the valid will fire. If the current txtAge.value is not a digit the valid will return 0 causing focus to remain on the control.

You would probably want to add a messagebox to alert the user as to what they did wrong. Returning 0 has a problem in that the user cannot move off the control until a valid entry is added, and may keep them from being able to use any controls to exit the form or get help.

Using the InputMask
The Input mask is probably the simplest way to implement our little example. You can just change txtAge.InputMask to 999. This will force all input to be a maximum of 3 digits.

A problem here is there is no way to alert the user why they can't enter anything but digits.

Using the Keypress event
The textbox has a keypress event that is fired each time a key is pressed. You can intercept the key and determine whether it is valid, and discard it or peform some action.

Add the following code to the keypress event of our example:
LPARAMETERS nKeyCode, nShiftAltCtrl

IF NOT BETWEEN(nKeyCode, 48, 57)

This will see if the key entered is a numeric. If not the NODEFAULT is called and the keypress is discarded. We could add a messagebox here as well informing the user of the error.

This has an advantage in that it allows the user to move off the control if they make a invalid entry.
Contributors: Roi Ledford

You will want to check if the char entered is a control char, so DEL, BS, ARROWS, etc. are not filtered. This can easily be done modifiying the IF clause as follows:
IF NOT (BETWEEN(nKeyCode, 48, 57) OR nKeyCode<32 OR nKeyCode=127)

Furio Filoseta
Category VFP Methods Category Exam 70-155 Hot Topic
( Topic last updated: 2010.06.08 07:59:25 PM )