Validate Input While the User Types

Visual Basic 6 and Access both provide developers with masked editing controls: text input controls that automatically format your input as you type it in based on a specific mask. For example, if you type 1234567890 into a masked input control that uses a telephone-number mask, the number is displayed as the string (123) 456-7890.

Note

VB 6 programmers accustomed to the ActiveX MaskedEdit control were disappointed to find . NET did not include a replacement. In . NET 2.0, the new MaskedTextBox fills the gap.

Masked input controls not only improve the presentation of certain values—they also prevent errors. Choosing the right mask ensures that certain characters will be rejected outright (for example, a telephone- number mask will not accept letters). Masked input controls also neatly avoid canonicalization errors, which occur when there is more than one way of representing the same information. For example, with the telephone number mask, the user will immediately realize that an area code is required, even if you don't specifically explain this requirement.

How do I do that?

.NET 2.0 includes a new control named MaskedTextBox that extends the TextBox control. Once you've added a MaskedTextBox to a form, you can set the mask in two ways:

  • You can choose one of the prebuilt masks.

  • You can define your own custom mask.

To set a mask, click the MaskedTextBox smart tag and select Set Mask. The Input Mask dialog box appears, with a list of commonly ...

Get Visual Basic 2005: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.