The Validate event and the accompanying CausesValidate property are new to VB6
and give programmers a much-needed replacement for older, more cumbersome techniques
of field validation. (See the section in this chapter entitled
In general, the best time to validate a field's contents is when
the user attempts to leave the field. The Validate event fires whenever the user
attempts to set focus to another field on the same form or when the form unloads
from memory while the current field has focus. A programmer can evaluate the state
of the data at that point and react to any error in the data either by:
Programmatically correcting the data error.
Setting the Validate event procedure's Cancel parameter to True in order to
prevent focus from leaving the control, thus forcing the user to fix whatever
problem was encountered.
You should take the following steps to implement field-level
validation with the Validate event:
Determine which controls (such as CancelButtons)
should not trigger the Validate event when
the user tries to set focus to them and
set the CausesValidation property of these
controls to False (default is True).
Write validation code (or call your own
validation routines) in the Validate event
procedure of all controls where you need
to have validation in place.
If your validation code decides that the
control's data is not valid, you can
• Fix the problem right there in the
• Force the focus to remain in the
current control (presumably so that the
user can rectify the problem) by setting
value of the Validate event's Cancel
parameter to True.
Listing 5.4 illustrates the use
of the Validate event procedure to perform validation
and to decide whether or not to keep focus on
the current control.
USING THE VALIDATE EVENT PROCEDURE
Private Sub txtAge_Validate(Cancel As Boolean)
If Not IsNumeric(txtAge.Text) Then
Cancel = True
ElseIf txtAge.Text < 21 Then
Beep 'give the user some minimal feedback
MsgBox "Enter an age greater than 21"
Cancel = True
'Following is not needed. Placed here for clarity
Cancel = False
Related topics on Field-Level Validation Techniques