Phoenix Logo

phoenix_title wx.lib.masked.maskededit

contains MaskedEditMixin class that drives all the other masked controls.

Masked Edit Overview


is a sublassed text control that can carefully control the user’s input based on a mask string you provide.

General usage example:

control = masked.TextCtrl( win, -1, '', mask = '(###) ###-####')

The example above will create a text control that allows only numbers to be entered and then only in the positions indicated in the mask by the # sign.

is a similar subclass of wxComboBox that allows the same sort of masking, but also can do auto-complete of values, and can require the value typed to be in the list of choices to be colored appropriately.

is actually a factory function for several types of masked edit controls:

masked.TextCtrl standard masked edit text box
masked.ComboBox adds combobox capabilities
masked.IpAddrCtrl adds special semantics for IP address entry
masked.TimeCtrl special subclass handling lots of types as values
masked.NumCtrl special subclass handling numeric values

It works by looking for a controlType parameter in the keyword arguments of the control, to determine what kind of instance to return. If not specified as a keyword argument, the default control type returned will be masked.TextCtrl.

Each of the above classes has its own set of arguments, but masked.Ctrl provides a single “unified” interface for masked controls.

What follows is a description of how to configure the generic masked.TextCtrl and masked.ComboBox; masked.NumCtrl and masked.TimeCtrl have their own demo pages and interface descriptions.

Initialization Parameters


Allowed mask characters and function:

Character Function
# Allow numeric only (0-9)
N Allow letters and numbers (0-9)
A Allow uppercase letters only
a Allow lowercase letters only
C Allow any letter, upper or lower
X Allow string.letters, string.punctuation, string.digits
& Allow string.punctuation only (doesn’t include all unicode symbols)
* Allow any visible character

explicit field boundary (takes no space in the control; allows mix of adjacent mask characters to be treated as separate fields, eg: ‘&|###’ means “field 0 = ‘&’, field 1 = ‘###’”, but there’s no fixed characters in between.

These controls define these sets of characters using string.letters, string.uppercase, etc. These sets are affected by the system locale setting, so in order to have the masked controls accept characters that are specific to your users’ language, your application should set the locale. For example, to allow international characters to be used in the above masks, you can place the following in your code as part of your application’s initialization code:

import locale
locale.setlocale(locale.LC_ALL, '')

The controls now also support (by popular demand) all “visible” characters, by use of the * mask character, including unicode characters above the standard ANSI keycode range. Note: As string.punctuation doesn’t typically include all unicode symbols, you will have to use includechars to get some of these into otherwise restricted positions in your control, such as those specified with &.

Using these mask characters, a variety of template masks can be built. See the demo for some other common examples include date+time, social security number, etc. If any of these characters are needed as template rather than mask characters, they can be escaped with , ie. N means “literal N”. (use \ for literal backslash, as in: r’CCC\NNN’.)


Masks containing only # characters and one optional decimal point character are handled specially, as “numeric” controls. Such controls have special handling for typing the ‘-‘ key, handling the “decimal point” character as truncating the integer portion, optionally allowing grouping characters and so forth. There are several parameters and format codes that only make sense when combined with such masks, eg. groupChar, decimalChar, and so forth (see below). These allow you to construct reasonable numeric entry controls.


Changing the mask for a control deletes any previous field classes (and any associated validation or formatting constraints) for them.


By default, masked edit controls use a fixed width font, so that the mask characters are fixed within the control, regardless of subsequent modifications to the value. Set to False if having the control font be the same as other controls is required. (This is a control-level parameter.)

Changed in version 2.9.5: The default is changed to False for numctrl only

(Applies to unicode systems only) By default, the default unicode encoding used is latin1, or iso-8859-1. If necessary, you can set this control-level parameter to govern the codec used to decode your keyboard inputs. (This is a control-level parameter.)
These other properties can be passed to the class when instantiating it:

Formatcodes are specified as a string of single character formatting codes that modify behavior of the control:

_  Allow spaces
!  Force upper
^  Force lower
R  Right-align field(s)
r  Right-insert in field(s) (implies R)
<  Stay in field until explicit navigation out of it

>  Allow insert/delete within partially filled fields (as
   opposed to the default "overwrite" mode for fixed-width
   masked edit controls.)  This allows single-field controls
   or each field within a multi-field control to optionally
   behave more like standard text controls.
   (See EMAIL or phone number autoformat examples.)

   *Note: This also governs whether backspace/delete operations
   shift contents of field to right of cursor, or just blank the
   erased section.

   Also, when combined with 'r', this indicates that the field
   or control allows right insert anywhere within the current
   non-empty value in the field.  (Otherwise right-insert behavior
   is only performed to when the entire right-insertable field is
   selected or the cursor is at the right edge of the field.*

,  Allow grouping character in integer fields of numeric controls
   and auto-group/regroup digits (if the result fits) when leaving
   such a field.  (If specified, .SetValue() will attempt to
   auto-group as well.)
   ',' is also the default grouping character.  To change the
   grouping character and/or decimal character, use the groupChar
   and decimalChar parameters, respectively.
   Note: typing the "decimal point" character in such fields will
   clip the value to that left of the cursor for integer
   fields of controls with "integer" or "floating point" masks.
   If the ',' format code is specified, this will also cause the
   resulting digits to be regrouped properly, using the current
   grouping character.
-  Prepend and reserve leading space for sign to mask and allow
   signed values (negative #s shown in red by default.) Can be
   used with argument useParensForNegatives (see below.)
0  integer fields get leading zeros
D  Date[/time] field
T  Time field
F  Auto-Fit: the control calulates its size from
   the length of the template mask
V  validate entered chars against validRegex before allowing them
   to be entered vs. being allowed by basic mask and then having
   the resulting value just colored as invalid.
   (See USSTATE autoformat demo for how this can be used.)
S  select entire field when navigating to new field



These controls have two options for the initial state of the control. If a blank control with just the non-editable characters showing is desired, simply leave the constructor variable fillChar as its default (‘ ‘). If you want some other character there, simply change the fillChar to that value. Note: changing the control’s fillChar will implicitly reset all of the fields’ fillChars to this value.

If you need different default characters in each mask position, you can specify a defaultValue parameter in the constructor, or set them for each field individually. This value must satisfy the non-editable characters of the mask, but need not conform to the replaceable characters.



These parameters govern what character is used to group numbers and is used to indicate the decimal point for numeric format controls. The default groupChar is ‘,’, the default decimalChar is ‘.’ By changing these, you can customize the presentation of numbers for your location.


formatcodes = ',', groupChar='\''                  allows  12'345.34
formatcodes = ',', groupChar='.', decimalChar=','  allows  12.345,34

(These are control-level parameters.)

The default “shiftDecimalChar” (used for “backwards-tabbing” until shift-tab is fixed in wxPython) is ‘>’ (for QUERTY keyboards.) for other keyboards, you may want to customize this, eg ‘?’ for shift ‘,’ on AZERTY keyboards, ‘:’ or ‘;’ for other European keyboards, etc. (This is a control-level parameter.)
This option can be used with signed numeric format controls to indicate signs via () rather than ‘-‘. (This is a control-level parameter.)
This option can be used to have a field or the control try to auto-complete on each keystroke if choices have been specified.

By default, DownArrow, PageUp and PageDown will auto-complete a partially entered field. Shift-DownArrow, Shift-UpArrow, PageUp and PageDown will also auto-complete, but if the field already contains a matched value, these keys will cycle through the list of choices forward or backward as appropriate. Shift-Up and Shift-Down also take you to the next/previous field after any auto-complete action.

Additional auto-complete keys can be specified via this parameter. Any keys so specified will act like PageDown. (This is a control-level parameter.)

Validating User Input

There are a variety of initialization parameters that are used to validate user input. These parameters can apply to the control as a whole, and/or to individual fields:

excludeChars A string of characters to exclude even if otherwise allowed
includeChars A string of characters to allow even if otherwise disallowed
validRegex Use a regular expression to validate the contents of the text box
validRange Pass a rangeas list (low,high) to limit numeric fields/values
choices A list of strings that are allowed choices for the control.
choiceRequired value must be member of choices list
compareNoCase Perform case-insensitive matching when validating against list. Note: for masked.ComboBox, this defaults to True.
emptyInvalid Boolean indicating whether an empty value should be considered invalid
validFunc A function to call of the form: bool = func(candidate_value) which will return True if the candidate_value satisfies some external criteria for the control in addition to the the other validation, or False if not. (This validation is applied last in the chain of validations.)
validRequired Boolean indicating whether or not keys that are allowed by the mask, but result in an invalid value are allowed to be entered into the control. Setting this to True implies that a valid default value is set for the control.
retainFieldValidation False by default; if True, this allows individual fields to retain their own validation constraints independently of any subsequent changes to the control’s overall parameters. (This is a control-level parameter.)
validator Validators are not normally needed for masked controls, because of the nature of the validation and control of input. However, you can supply one to provide data transfer routines for the controls.
raiseOnInvalidPaste False by default; normally a bad paste simply is ignored with a bell; if True, this will cause a ValueError exception to be thrown, with the .value attribute of the exception containing the bad value.
stopFieldChangeIfInvalid False by default; tries to prevent navigation out of a field if its current value is invalid. Can be used to create a hybrid of validation settings, allowing intermediate invalid values in a field without sacrificing ability to limit values as with validRequired. NOTE: It is possible to end up with an invalid value when using this option if focus is switched to some other control via mousing. To avoid this, consider deriving a class that defines _LostFocus() function that returns the control to a valid value when the focus shifts. (AFAICT, The change in focus is unpreventable.)

Coloring Behavior

The following parameters have been provided to allow you to change the default coloring behavior of the control. These can be set at construction, or via the .SetCtrlParameters() function. Pass a color as string e.g. ‘Yellow’:

emptyBackgroundColour Control Background color when identified as empty. Default=White
invalidBackgroundColour Control Background color when identified as Not valid. Default=Yellow
validBackgroundColour Control Background color when identified as Valid. Default=white

The following parameters control the default foreground color coloring behavior of the control. Pass a color as string e.g. ‘Yellow’:

foregroundColour Control foreground color when value is not negative. Default=Black
signedForegroundColour Control foreground color when value is negative. Default=Red


Each part of the mask that allows user input is considered a field. The fields are represented by their own class instances. You can specify field-specific constraints by constructing or accessing the field instances for the control and then specifying those constraints via parameters.


This parameter allows you to specify Field instances containing constraints for the individual fields of a control, eg: local choice lists, validation rules, functions, regexps, etc. It can be either an ordered list or a dictionary. If a list, the fields will be applied as fields 0, 1, 2, etc. If a dictionary, it should be keyed by field index. the values should be a instances of maskededit.Field.

Any field not represented by the list or dictionary will be implicitly created by the control.


fields = [ Field(formatcodes='_r'), Field('choices=['a', 'b', 'c']) ]


fields = {
           1: ( Field(formatcodes='_R', choices=['a', 'b', 'c']),
           3: ( Field(choices=['01', '02', '03'], choiceRequired=True)

The following parameters are available for individual fields, with the same semantics as for the whole control but applied to the field in question:

fillChar if set for a field, it will override the control’s fillChar for that field
groupChar if set for a field, it will override the control’s default
defaultValue sets field-specific default value; overrides any default from control
compareNoCase overrides control’s settings
emptyInvalid determines whether field is required to be filled at all times
validRequired if set, requires field to contain valid value

If any of the above parameters are subsequently specified for the control as a whole, that new value will be propagated to each field, unless the retainFieldValidation control-level parameter is set.

formatcodes Augments control’s settings
excludeChars ‘ ‘ ‘
includeChars ‘ ‘ ‘
validRegex ‘ ‘ ‘
validRange ‘ ‘ ‘
choices ‘ ‘ ‘
choiceRequired ‘ ‘ ‘
validFunc ‘ ‘ ‘

Control Class Functions

Returns the value specified (or the control’s text value not specified) without the formatting text. In the example above, might return phone no=‘3522640075’, whereas control.GetValue() would return ‘(352) 264-0075’
Returns the control’s value to its default, and places the cursor at the beginning of the control.

Does “smart replacement” of passed value into the control, as does the .Paste() method. As with other text entry controls, the .SetValue() text replacement begins at left-edge of the control, with missing mask characters inserted as appropriate. .SetValue will also adjust integer, float or date mask entry values, adding commas, auto-completing years, etc. as appropriate. For “right-aligned” numeric controls, it will also now automatically right-adjust any value whose length is less than the width of the control before attempting to set the value. If a value does not follow the format of the control’s mask, or will not fit into the control, a ValueError exception will be raised.


mask = '(###) ###-####'
    .SetValue('1234567890')           => '(123) 456-7890'
    .SetValue('(123)4567890')         => '(123) 456-7890'
    .SetValue('(123)456-7890')        => '(123) 456-7890'
    .SetValue('123/4567-890')         => illegal paste; ValueError

mask = '#{6}.#{2}', formatcodes = '_,-',
    .SetValue('111')                  => ' 111   .  '
    .SetValue(' %9.2f' % -111.12345 ) => '   -111.12'
    .SetValue(' %9.2f' % 1234.00 )    => '  1,234.00'
    .SetValue(' %9.2f' % -1234567.12345 ) => insufficient room; ValueError

mask = '#{6}.#{2}', formatcodes = '_,-R'  # will right-adjust value for right-aligned control
    .SetValue('111')                  => padded value misalignment ValueError: "       111" will not fit
    .SetValue('%.2f' % 111 )          => '    111.00'
    .SetValue('%.2f' % -111.12345 )   => '   -111.12'
Returns True if the value specified (or the value of the control if not specified) passes validation tests
Returns True if the value specified (or the value of the control if not specified) is equal to an “empty value,” ie. all editable characters == the fillChar for their respective fields.
Returns True if the value specified (or the value of the control if not specified) is equal to the initial value of the control.
Recolors the control as appropriate to its current settings.

This function allows you to set up and/or change the control parameters after construction; it takes a list of key/value pairs as arguments, where the keys can be any of the mask-specific parameters in the constructor.


ctl = masked.TextCtrl( self, -1 )
ctl.SetCtrlParameters( mask='###-####',
This function allows you to retrieve the current value of a parameter from the control.
Note: Each of the control parameters can also be set using its
own Set and Get function. These functions follow a regular form: All of the parameter names start with lower case; for their corresponding Set/Get function, the parameter name is capitalized.


Note: After any change in parameters, the choices for the
control are reevaluated to ensure that they are still legal. If you have large choice lists, it is therefore more efficient to set parameters before setting the choices available.
.SetFieldParameters(field_index, **kwargs)
This function allows you to specify change individual field parameters after construction. (Indices are 0-based.)
.GetFieldParameter(field_index, parametername)
Allows the retrieval of field parameters after construction

The control detects certain common constructions. In order to use the signed feature (negative numbers and coloring), the mask has to be all numbers with optionally one decimal point. Without a decimal (e.g. ‘######’, the control will treat it as an integer value. With a decimal (e.g. ‘###.##’), the control will act as a floating point control (i.e. press decimal to ‘tab’ to the decimal position). Pressing decimal in the integer control truncates the value. However, for a true numeric control, masked.NumCtrl provides all this, and true numeric input/output support as well.

Check your controls by calling each control’s .IsValid() function and the .IsEmpty() function to determine which controls have been a) filled in and b) filled in properly.

Regular expression validations can be used flexibly and creatively. Take a look at the demo; the zip-code validation succeeds as long as the first five numerals are entered. the last four are optional, but if any are entered, there must be 4 to be valid.

masked.Ctrl Configuration

masked.Ctrl works by looking for a special controlType parameter in the variable arguments of the control, to determine what kind of instance to return. controlType can be one of:


These constants are also available individually, ie, you can use either of the following:

from wx.lib.masked import MaskedCtrl, controlTypes
from wx.lib.masked import MaskedCtrl, COMBO, TEXT, NUMBER, IPADDR

If not specified as a keyword argument, the default controlType is controlTypes.TEXT.

class_summary Classes Summary

Field This class manages the individual fields in a masked edit control.
MaskedEditAccessorsMixin To avoid a ton of boiler-plate, and to automate the getter/setter generation
MaskedEditMixin This class allows us to abstract the masked edit functionality that could