Character-Based Masked Edit

Introduction

Most masked edit controls allow you to set the mask of the entire edit control, making each character have the same mask. Sometimes this is ok, but sometimes it is not. For example, you may have a 6-digit part number, where the first digit can only be the letters A or B, the second digit can only be a vowel, and the remaining digits can be 0 through 9 inclusive. Try doing that with a conventional masked edit control.

With my masked edit control, you will be able to set the mask for each character in an edit control. Although I've totally written this control from scratch, I got the idea from a former (and very brilliant) co-worker of mine, Dave Kelly.

How to construct the mask

To set the mask, you will need to call the Init() function and pass it a mask and optional initial data. The mask is constructed so that each character is inside the brackets, and all static characters (characters not enterable by the user, such as a dash or a slash) are outside the brackets. Dashes can be used inside the brackets to indicate a range of characters (based on the ASCII value of the start and end character).

Example masks

The part number mentioned above in the Introduction: "[AB][AEIOU][0-9][0-9][0-9][0-9]"
Telephone number in the 719 area code: "(719) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]"
A 2-digit, alphanumeric, not case-sensitive: "[A-Za-z0-9][A-Za-z0-9]"

The demo project is a test app in which you can enter a mask, or you can select a pre-defined mask from the combobox. Click the "Set Mask" buttons to set the mask of the edit control that is next to it.

Data exchange

To get the data out of the control, call the function GetData(). This function will return a string of characters that are enterable by the user (not static characters).

To set the data in the control, call the function SetData(), passing it a CString of the data you want prefilled.

You can always call GetWindowText() to get the data WITH the static characters in it. SetWindowText() can be called as well, but be careful that your string parameter will not conflict with your mask.

There is a DDX_CmEdit() function as well, so you can associate an edit control with a CString. Just call UpdateData() to do the data exchange.

Prompt character

The default prompt character is set to be an underscore. However, you can change this by calling the SetPromptChar() function.

Downloads

Download demo project - 23 KB
Download source - 5 KB