skip to content »

Vb validating textbox

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.

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).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.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.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.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. Imagine that you have five controls on a form: a required field (a Text Box control, txt Required, that can't contain an empty string), a numeric field, txt Numeric, 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 Causes Validation properties to False.

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!

Visual Basic 6's validation scheme has two flaws, though.

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.

In fact, this technique can only enforce field-level validation; it does nothing for record-level validation.