Text Validation Sample

  • Using regular expressions in a custom TextBox control

  • Using a MaskedTextBox control

To get samples and instructions for installing them, see the following:

  • Click Samples on the Visual Studio Help menu.

    For more information, see Locating Sample Files.

  • The most recent versions and the complete list of samples are available on the Visual Studio 2008 Samples Web site.

  • You can also locate samples on your computer's hard disk. By default, samples and a Readme file are copied to a folder under \Program Files\Visual Studio 9\Samples\. For Visual Studio Express Editions, all samples are located on the Internet.

To run this sample

  • Press F5.

Demonstrates

This sample shows how you can create a set of special-purpose text boxes that are designed for a specific type of input. This sample includes text boxes for e-mail addresses, IP addresses, and phone numbers.

The MaskedTextBox control provides validation as the user types, so incorrect text never appears in the MaskedTextBox.

The RegExTextBox class, derived from TextBox in this sample, serves at the base class for several other controls. This class validates the contents of the TextBox control against a given regular expression. When the user clicks the Validate button on the main form, the code loops through the controls collection to find all the RegExTextBox controls, then casts them to that base type to call the IsValid property. If the input is invalid, the TextBox text color will be red.