Validate Event, CausesValidation Property Example

The example uses three controls to demonstrate the use of the Validate event and CausesValidation property. By default, the CausesValidation property of the two TextBox controls are set to True. Thus when you try to shift the focus from one TextBox to the other, the Validate event occurs. If Text1 doesn't contain a date, or if Text2 doesn't contain a number larger than 10, the shift of focus is prevented. Because the CausesValidation property of the Command1 control is set to False, however, you can always click the Help button.

To try the example, place one CommandButton and two TextBox controls on a form. Paste the code into the Declarations section of the form and run the project. Attempt to shift the focus by pressing the Tab key.

Private Sub Form_Load()
   ' Set the button's CausesValidation property to False. When the user 
   ' clicks the button, the Validate event does not occur. 
   ' Set the Caption property of the button to "Help".
   With Command1
      .CausesValidation = False
      .Caption = "Help"
   End With

   Show
   With Text1 ' Select text of Text1 and set focus to it.
      .SelLength = Len(Text1.Text)
      .SetFocus
   End With
End Sub

Private Sub Command1_Click()
   ' Give the user help when the button is clicked.
   MsgBox _
   "Text1 must be set to a date." & VbCrLF & _
   "Text2 must be a number less than 10."
End Sub

Private Sub Text1_Validate(KeepFocus As Boolean)
   ' If the value is not a date, keep the focus, unless the user
   ' clicks Help.
   If Not IsDate(Text1.Text) Then 
      KeepFocus = True
      MsgBox "Please insert a date in this field.", ,   "Text1"
   End if
End Sub
   
Private Sub Text2_Validate(KeepFocus As Boolean)
   ' If the value is a number larger than 10, keep the focus.
   If Not IsNumeric(Text2.Text) Or Val(Text2.Text) > 10 Then 
      KeepFocus = True
MsgBox _
"Please insert a number less than or equal to 10.", , "Text2"
   End If
End Sub