Using Regular Expressions with the MaskedTextBox Control in Visual Basic
This example demonstrates how to convert simple regular expressions to work with the MaskedTextBox control.
The standard MaskedTextBox masking language is based on the one used by the Masked Edit control in Visual Basic 6.0 and should be familiar to users migrating from that platform.
Regular expression element
Any single digit between 0 and 9. Entry required.
Digit or space. Entry optional.
Digit or space. Entry optional. If this position is left blank in the mask, it will be rendered as a space. Plus (+) and minus (-) signs are allowed.
ASCII letter. Entry required.
ASCII letter. Entry optional.
Character. Entry required.
Character. Entry optional.
Alphanumeric. Entry optional.
Culture-appropriate decimal placeholder.
Culture-appropriate thousands placeholder.
Culture-appropriate time separator.
Culture-appropriate date separator.
Culture-appropriate currency symbol.
Converts all characters that follow to lowercase.
Converts all characters that follow to uppercase.
Undoes a previous shift up or shift down.
Escapes a mask character, turning it into a literal. "\\" is the escape sequence for a backslash.
All other characters.
Literals. All non-mask elements will appear as themselves within MaskedTextBox.
All other characters.
The decimal (.), thousandths (,), time (:), date (/), and currency ($) symbols default to displaying those symbols as defined by the application's culture. You can force them to display symbols for another culture by using the FormatProvider property.
Although you can use regular expressions and masks to validate user input, they are not completely equivalent. Regular expressions can express more complex patterns than masks, but masks can express the same information more succinctly and in a culturally relevant format.
The following table compares four regular expressions and the equivalent mask for each.
The / character in the mask is a logical date separator, and it will appear to the user as the date separator appropriate to the application's current culture.
A date (day, month abbreviation, and year) in United States format in which the three-letter month abbreviation is displayed with an initial uppercase letter followed by two lowercase letters.
United States phone number, area code optional. If the user does not wish to enter the optional characters, she can either enter spaces or place the mouse pointer directly at the position in the mask represented by the first 0.
A currency value in the range of 0 to 999999. The currency, thousandth, and decimal characters will be replaced at run-time with their culture-specific equivalents.