Automate data validation in VB6 with CausesValidation and Validate
Takeaway: Don't let invalid user data problems sneak up on you—prevent them by developing programs that take into account data validation. Find out how you can automate the data validation process in VB6 using the CausesValidation property and the Validate event procedure.
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!
SponsoredWhite Papers, Webcasts, and Downloads
- Using the Six Laws of Persuasion in Negotiations Global Knowledge
- 7 Things Every System Administrator Should Know About OpenSSH Global Knowledge
- TCP/IP Troubleshooting Global Knowledge
- BitLocker: Is It Really Secure? Global Knowledge
- Ethical Hacking and Risk Assessments Global Knowledge
Article Categories
- Security
- Security Solutions, IT Locksmith
- Networking and Communications
- E-mail Administration NetNote, Cisco Routers and Switches
- CIO and IT Management
- Project Management, CIO Issues, Strategies that Scale
- Desktops, Laptops & OS
- Windows 2000 Professional, Microsoft Word, Microsoft Excel, Microsoft Access, Windows XP,
- Data Management
- Oracle, SQL Server
- Servers
- Windows NT, Linux NetNote, Windows Server 2003
- Career Development
- Geek Trivia
- Software/Web Development
- Web Development Zone, Visual Basic, .NET

