Data validation is an important part of many programs. Ensuring that the user has entered valid data can prevent a lot of problems down the road. In VB6, you can partially automate the process using the CausesValidation property and the Validate event procedure.
The process works when the user tries to shift the focus from the control, usually a TextBox, whose data you want to validate. If the control that is to receive the focus has its CausesValidation property set to True (the default), then the first control's Validate event fires. You can place code in this event procedure to perform the validation and take the appropriate action, such as displaying a message, if the validation fails. Also, if code in this procedure sets Cancel to True, the focus remains with the control rather than moving.
Here's an example of a Validate event procedure that checks to see if the value entered in TextBox named Text1 is greater than 0; if it's not, it displays a message and keeps the focus on the TextBox:
Private Sub Text1_Validate(Cancel As Boolean)
If Val(Text1.Text) <= 0 Then
Cancel = True
MsgBox "You must enter a value greater than 0."
End If
End Sub
Take the time to worry about data validation before invalid user data comes back to haunt you later.
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!



