Vb net validating input

The keys to the new validation features are the Validate event and the Causes Validation property.

They work together as follows: When the input focus leaves a control, Visual Basic checks the Causes Validation property of the control that is about to receive the focus.

vb net validating input-58

Typically, you do it when the user closes the form: Private Sub Form_Query Unload(Cancel As Integer, Unload Mode As Integer) ' You can't close this form without validating the current field.

If Unload Mode = vb Form Control Menu Then On Error Resume Next Validate Controls If Err = 380 Then ' The current field failed validation.

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 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 Text Box, and then move to the second field.

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 Unload Mode = vb Form Control Menu Then On Error Resume Next Dim ctrl As Control ' Give the focus to each control on the form, and then ' validate it. Validate Controls If Err = 380 Then ' Validation failed, refuse to close.

Try clicking on the Help or Cancel buttons: No Validate event will fire this time because you set the Causes Validation property for each of these controls to False.

Tags: , ,