VB6 beginners tutorial - Learn VB6

Advanced VB6 tutorial - Learn Advanced VB6

Systems Analysis - System analysis and Design tutorial for Software Engineering

Browse Topics

- Getting started
- Data Types
- Modules
- Operators in VB6
- VB6 Variable
- VB6 Procedures
- VB6 Control Structures
- Loops in VB6
- VB6 Exit Do & With End With
- Arrays in VB6
- User-Defined Data Types
- VB6 Constants
VB6 Built-in Functions
- Date and Time in VB6
- VB6 Controls
- TextBox Control
- ComboBox & OptionButton
- Label & Frame
- PictureBox & ImageBox
- Timer Control
- ListBox & ComboBox
- VB6 ScrollBar
- Control Arrays in VB6
- Files controls in VB6
- VB6 CheckBox
- Forms in VB6
- Menus in VB6
- MDI Form in VB6
- InputBox
- MessageBox
- Mouse events
- Mouse Move
- Error Handling
Error Handling (2)
VB6 Database

You are here: Visual Basic > VB6 (Beginners Tutorial)

Previous Page | Table of Contents | Next Page

The CausesValidation Property and the Validate Event - Visual Basic 6 TextBox Control

Visual Basic 6 has finally come up with a solution for most of the validation issues that have afflicted Visual Basic developers for years. As you'll see in a moment, the Visual Basic 6 approach is simple and clean; it really astonishes me that it took six language versions to deliver such a lifesaver. The keys to the new validation features are the Validate event and the CausesValidation property. They work together as follows: When the input focus leaves a control, Visual Basic checks the CausesValidation property of the control that is about to receive the focus. If this property is True, Visual Basic fires the Validate event in the control that's about to lose the focus, thus giving the programmer a chance to validate its contents and, if necessary, cancel the focus shift.

Let's try a practical example. Imagine that you have five controls on a form: a required field (a TextBox control, txtRequired, that can't contain an empty string), a numeric field, txtNumeric, that expects a value in the range 1 through 1000, and three push buttons: OK, Cancel, and Help. (See the figure below.) You don't want to perform validation if the user presses the Cancel or Help buttons, so you set their CausesValidation properties to False. The default value for this property is True, so you don't have to modify it for the other controls. Run the sample program on the companion CD, type something in the required TextBox, and then move to the second field. Because the second field's CausesValidation property is True, Visual Basic fires a Validate event in the first TextBox control:

Private Sub txtRequired_Validate(Cancel As Boolean)
' Check that field is not empty.
If txtRequired.Text = "" Then
MsgBox "Please enter something here", vbExclamation
Cancel = True
End If
End Sub

If the Cancel parameter is set to True, Visual Basic cancels the user's action and takes the input focus back on the txtRequired control: No other GotFocus and LostFocus events are generated. On the other hand, if you typed something in the required field, the focus will now be on the second field (the numeric text box). Try clicking on the Help or Cancel buttons: No Validate event will fire this time because you set the CausesValidation property for each of these controls to False. Instead, click on the OK button to execute the Validate event of the numeric field, where you can check it for invalid characters and valid range.

A demonstration program that lets you experiment with the new Visual Basic Validate features
A demonstration program that lets you experiment with the new Visual Basic Validate features

Private Sub txtNumeric_Validate(Cancel As Boolean)
If Not IsNumeric(txtNumeric.Text) Then
Cancel = True
ElseIf CDbl(txtNumeric.Text) < 1 Or CDbl(txtNumeric.Text) > 1000 Then
Cancel = True
End If
If Cancel Then
MsgBox "Please enter a number in range [1-1000]", vbExclamation
End If
End Sub

In some circumstances, you might want to programmatically validate the control that has the focus without waiting for the user to move the input focus. You can do it with the form's ValidateControls method, which forces the Validate event of the control that has the input focus. Typically, you do it when the user closes the form:

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
' You can't close this form without validating the current field.
If UnloadMode = vbFormControlMenu Then
On Error Resume Next
If Err = 380 Then
' The current field failed validation.
Cancel = True
End If
End If
End Sub

Checking the UnloadMode parameter is important; otherwise, your application will mistakenly execute a ValidateControls method when the user clicks on the Cancel button. Note that ValidateControls returns an error 380 if Cancel was set in the Validate event procedure of the control that had the focus.

Visual Basic 6's validation scheme has two flaws, though. If your form has a CommandButton whose Default property is set to True, pressing the Enter key while the input focus is on another control results in a click on the CommandButton control but doesn't fire a Validate event, even if the CausesValidation property of the CommandButton control is set to True. The only way to solve this problem is to invoke the ValidateControls method from within the default CommandButton control's Click event procedure.

The second flaw is that the Validate event doesn't fire when you're moving the focus from a control whose CausesValidation property is False, even if the control that receives the focus has its CausesValidation property set to True.

The new Visual Basic 6 validation mechanism is simple and can be implemented with little effort. But it isn't the magic answer to all your validation needs. In fact, this technique can only enforce field-level validation; it does nothing for record-level validation. In other words, it ensures that one particular field is correct, not that all fields in the form contain valid data. To see what I mean, run the demonstration program, enter a string in the first field, and press Alt+F4 to close the form. Your code won't raise an error, even if the second field doesn't contain a valid number! Fortunately, it doesn't take much to create a generic routine that forces each control on the form to validate itself:

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
' You can't close this form without validating all the fields on it.
If UnloadMode = vbFormControlMenu Then
On Error Resume Next
Dim ctrl As Control
' Give the focus to each control on the form, and then
' validate it.
For Each ctrl In Controls
If Err = 0 Then
' Don't validate controls that can't receive input focus.
If Err = 380 Then
' Validation failed, refuse to close.
Cancel = True: Exit Sub
End If
End If
End If
End Sub

The CausesValidation property and the Validate event are shared by all the intrinsic controls that are able to get the focus as well as by most external ActiveX controls, even those not specifically written for Visual Basic. This is possible because they are extender features, provided by the Visual Basic runtime to all the controls placed on a form's surface.

One Visual Basic operator has great potential when it comes time to validate complex strings but is neglected by most Visual Basic developers. Let's say you have a product code that consists of two uppercase characters followed by exactly three digits. You might think that you need some complex string functions to validate such a string until you try the Like operator, as follows:

If "AX123" Like "[A-Z][A-Z]###" Then Print "OK"

More on VB6 TextBox Controls

See Also


Previous Page | Table of Contents | Next Page


Home | About Us | Privacy Policy | Contact Us

Copyright © | All Rights Reserved