Visual Basic Concepts

Visual Studio 6.0

Validating Control Data by Restricting Focus

The Validate event and CausesValidation property are used in tandem to verify the input to a control before allowing the user to shift focus away from that control. For example, imagine an application with several text boxes and a Help button. When each text box receives the focus, you want to prevent the user from shifting the focus until the text box's particular validation criteria are met; however, you also want to allow users to click the Help button at any time. To do this, set the validation criteria in the Validate event and set the CausesValidation property of the Help button to False. If the property is set to True (the default setting), the Validate event will occur on the first control. If the property is set to False, the Validate event on the first control will be preempted from occurring.

The Validate event is more suited to validating data entry than the LostFocus event because the LostFocus event (by definition) occurs after the focus has shifted. In contrast, by using the Validate event you can prevent the focus from ever shifting to another control until all validation rules have been met.

Possible Uses

  • A data entry application needs to perform more sophisticated data entry validation than can be provided by the Masked Edit control, or the validation occurs in a business rule.

  • A form needs to prevent users from moving off a control using the TAB key or an accelerator until data has been entered in a field.

  • An ActiveX document running inside Internet Explorer needs a way for the user to finish an operation on the form before the script moves the focus programmatically.

Control the Focus in the Validate Event

The Validate event includes a keepfocus argument. When the argument is set to True, the control will retain the focus. This effectively prevents the user from clicking any other control.