October 19, 2009

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
ValidateControls
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
Err.Clear
ctrl.SetFocus
If Err = 0 Then
' Don't validate controls that can't receive input focus.
ValidateControls
If Err = 380 Then
' Validation failed, refuse to close.
Cancel = True: Exit Sub
End If
End If
Next
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"

Disclaimer:
The above article doesn't give you any guarantee and the sole purpose of this article is to share my learning in the way I understood. Any comments to refine this article are welcome with great pleasure. Please report any breaking link by commenting below.

No comments:

Post a Comment

Comment will be published after moderation only. Do not advertise here.

Receive all updates via Facebook. Just Click the Like Button Below

You can also receive Free Email Updates:

dgpride - Study Zone - Free Books - Tamil Lyrics

Copyright © 2008 -2012 dgpride. All rights reserved.

Subject/Topics

2 Marks (26) 8051 (1) AC Machines (7) Animations (1) Anna University Chennai (31) Arduino (4) ARM (3) Audio (1) Basic C Concepts (8) Basic Electronics (13) Basic principles (9) Book list (1) CAD (1) Chemical (2) Circuit theory (6) Civil (2) Cloud Computing (1) Communication (4) Competitive exams (2) Computer Architecture (4) Control system and components (9) CSE (40) Curriculum (4) DC Machines (9) Did you know (14) Digital (13) DLC (4) Documentation (1) DSP (1) EC 2201 (3) ECE (45) EDC (1) EEE (34) EIE (63) Electrical (35) Electronics (43) Electroplating (2) Emacs (1) Embedded basics (19) Embedded C Programming (19) Embedded Linux (5) Embedded System (22) Engineering basics (15) Environmental Science (1) Fibre Optics (1) Filters (2) FPGA (1) GATE (3) General (7) GNU (4) Handwritten (1) Hobbyist (15) How to (8) HTML (3) Humanities (2) IC Engines (7) ICE (5) Industrial Electronics (10) Industrial Instrumentatin (2) industrial process (2) Instrumentation (21) IoT (2) IT (2) Laboratory Manuals (17) LabVIEW (2) Lesson notes (2) LIC (2) Links (9) Linux (8) Magnetics (1) Management (1) Mechanical (5) Mechatronics (9) Microcontrollers (14) Microprocessors (9) Microsoft (1) Motivation (1) Must Know (11) Networks (1) NuttX (1) Objective type (1) Open Source (1) Opportunities (7) Oscillators (2) Part Time (1) Physics (1) Post Graduation (1) Power Electronics (12) Power Plant Engineering (2) Power Supplies (2) Previous GATE Papers (1) Process Control (2) Project (4) Protocol (1) R2008 (11) R2009 (1) R2013 (1) Recruitment (2) Research (2) Robotics (9) RTOS (3) Signal Processing (8) Signals and Systems (4) SMPS (1) Software tutorial (4) Stepper Motor (2) Syllabus (5) Texas Instruments (2) Thermodynamics (2) Training and Placement (6) Transducer Engineering (2) Transformer (2) Transmission (1) Tutorials (48) Two Marks (26) U-Boot (1) University Question Papers (16) Verilog (1) Video (4) Virtual Instrumentation (3) Visual Basic (21) VLSI (11) Web designing (4) Wi-Fi (3) Wireless (6)