Vb code for validating textbox
The Validate event fires whenever the user attempts to set focus to another field on the same form or when the form unloads from memory while the current field has focus.A programmer can evaluate the state of the data at that point and react to any error in the data either by: Listing 5.4 illustrates the use of the Validate event procedure to perform validation and to decide whether or not to keep focus on the current control.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.1000 Then Cancel = True End If If Cancel Then Msg Box "Please enter a number in range [1-1000]", vb Exclamation 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.Note that Validate Controls returns an error 380 if Cancel was set in the Validate event procedure of the control that had the focus.
The new Visual Basic 6 validation mechanism is simple and can be implemented with little effort.
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_Query Unload(Cancel As Integer, Unload Mode As Integer) ' You can't close this form without validating all the fields on it. Set Focus If Err = 0 Then ' Don't validate controls that can't receive input focus.
If your form has a Command Button 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 Command Button control but doesn't fire a Validate event, even if the Causes Validation property of the Command Button control is set to True.
The only way to solve this problem is to invoke the Validate Controls method from within the default Command Button control's Click event procedure.But it isn't the magic answer to all your validation needs.