Freetutes.com

VB6 beginners tutorial - Learn VB6

Advanced VB6 tutorial - Learn Advanced VB6

VB .NET - Learn Visual Basic .NET

Systems Analysis - System analysis and Design tutorial for Software Engineering


You are here: Visual Basic > Advanced VB6 tutorial > Chapter 5

VB - Validate Event and CausesValidation Property in Visual Basic 6

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 "Validation With GotFocus and LostFocus Events".)

The Validate Event

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:

  1. 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).

  2. 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.

  3. If your validation code decides that the control's data is not valid, you can either:
    • Fix the problem right there in the validation code.
    • Force the focus to remain in the current control (presumably so that the user can rectify the problem) by setting the
    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.

LISTING 5.4
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
Else
Cancel = False
End If
End Sub

Related topics on Field-Level Validation Techniques

See Also


  

<< Previous | Contents | Next >>

Home | About Us | Privacy Policy | Contact Us

Copyright © Freetutes.com | All Rights Reserved