Introduction

The mask input automatically transforms user input to match a provided format. Used appropriately, mask inputs can provide an improved user experience by removing any ambiguity for the desired value (for example a phone number or social security number).

Mask Input Overview

2 mins

Basic example

Load Live Example

Masks

The mask is the desired format of the input. It is passed to the mask prop where it is parsed for tokens. The mask is comprised of:

  • Tokens - A string representation of a user-editable region. Shown in white below.
  • String literals - Any character that is not a token. Not user-editable. Shown in orange below.
Image of mask string with tokens and string literals in different colors.

Built-in tokens

The mask input comes with 4 built-in tokens:

  • h - Accepts a hexadecimal character (0-9a-fA-F).
  • # - Accepts a digit character.
  • a - Accepts an alphabetical character.
  • * - Accepts any character.
Load Live Example

Escaping built-ins

If you need to use one of the built-in tokens as a string literal in your mask, you can escape them with \. Here we are escaping the pound sign # to use in our hex color:

Modes

The mask input supports 3 entry modes:

  • Shift (default)
  • Replace
  • Select

Shift & replace mode

By default, the characters of a mask are automatically shifted forward when typing. This is notable when a mask is already populated and you place the cursor at or near the beginning of the input and begin typing. The characters following your cursor are "shifted" forward as you type. In replace mode, however, subsequent characters are overwritten with a new value:

Load Live Example

Select mode

In select mode, equivalent char type tokens are grouped into selectable text ranges. FormKit automatically selects these text ranges when clicking or focusing the input. These selection ranges are maintained as the user is typing. When used tastefully, this produces a clear UX as the user is aware of what value they are expected to enter.

Additionally, when an input is in select mode, the user can use the arrow or tab keys to shift their focus from one selection range to another:

Load Live Example
Select mode options
The selectDirection token property controls which direction new characters flow into the selected range. You can fill "empty" selection characters with a predetermined value (like leading zeros "0") by using the selectFill property. See token properties.

Tokens

Creating new tokens

What if a pattern can accept letters or numbers in the same position? It’s relatively simple to create new tokens. There are 2 types of tokens:

  • char accepts a single character.
  • enum accepts any strings from an array of possible values.

The following properties must be defined to create a new token:

For example, a new token that accepts letters and numbers, and is represented by the letter z in the mask string would look like this:

Placeholders should not match pattern
Any placeholder you define should not match the Regex pattern provided in the token definition.

Add tokens via prop

To pass a new token to the mask input, you can use the tokens prop which expects an object with keys that match the token property. For example, our new token in the above example can be applied directly:

Load Live Example

Add tokens globally

To register your mask tokens globally, extend the config property of your global FormKit configuration:

Load Live Example

Modify tokens

In addition to creating new tokens, the tokens prop can also modify existing tokens. Any value provided to the tokens prop will be merged into the existing tokens for that input. For example, the digit token’s (#) has no selectFill by default. To add one, simply extend it:

Load Live Example

Char tokens

char tokens accept a single character. In order for a character to be accepted, it must match the token.pattern regular expression. The four built in tokens (h, #, a, and *) are all char type tokens.

In select mode, char tokens are grouped together into a selection range.

Placeholders
A char token should only ever represent 1 character, and its placeholder should also only be a single character in length.

Enum Tokens

Enum tokens allow for variable length masks within a predefined set of options. As a user begins to type, the enum token’s value will change to the first matching value, and the selection range will reflect the currently unmatched characters. In practice, this operates much like an autocomplete for that specific token. Additionally, users can cycle through available options for a given token by hitting the up/down arrow keys.

A date with auto-completing month names could be well represented with enums:

Load Live Example
Select mode requirement
Enums are only supported in select mode. When any enum token is found in a mask string, the mode of the input is forcibly set to select.

Groups

Groups are a way to to treat multiple mask characters as a single unit. You create a group by surrounding the desired mask characters in {}:

On their own, groups don't do anything unless you define group options.

Group options

Group options allow you to apply functionality to an entire group using a pipe | followed by the option name and any arguments. The available options are:

  • repeat — allows a group to be repeated an infinite number of times.
  • placeholder — A character to hold space prior to user input.
Group placeholders
A placeholder defined within a group has a higher specificity than a placeholder defined in the token definition and will override it.

Option parameters

Arguments can be passed to a group option by using a colon, such as placeholder:+, where the plus symbol + is passed to the placeholder option.

You can string group options together:

Load Live Example
Can't be used in select mode
Groups cannot be used in select mode. An exception will be thrown.

Prefix & suffix

You can ensure certain characters always appear at the beginning or end of an input by using the prefix and suffix props, respectively:

Load Live Example
Values can't match the mask
Your prefix and suffix content can't match the mask. For instance, if your mask has a digit token #, your prefix/suffix can't contain numbers.

Running the mask in reverse

In specific circumstances, you may want to run your mask in reverse. The mask will test if user input fulfills the mask from right to left. This is common in currency-type inputs and can be applied by adding the reverse prop:

Load Live Example
Shift mode requirement
Running a mask in reverse only works in shift mode.

Mask values

Incomplete values

A mask’s value is not considered "complete" until the user has filled the entire pattern. Until that point, FormKit will consider the value of the input "empty". This makes it convenient to use with validation rules like required. However, if you’d like to accept incomplete values, you can via the allow-incomplete prop:

Load Live Example

Unmasked values

By default, the value of a mask input includes the formatting provided via the mask prop. However, if you'd like the raw unmasked value with the string literals removed, you can use the unmask-value prop:

Load Live Example

Hiding the mask

By default, the mask input displays each token’s placeholder character. You can disable this behavior (except in select mode) while still applying formatting automatically via the show-mask prop:

Load Live Example

Props & Attributes

Prop Type Default Description
allow-incompletebooleanfalseBy default, the value of a mask input is empty until the pattern is complete. This prop allows the input to use incomplete values.
maskstringnoneThe mask to apply. This is a string composed of tokens (like “#”) and literal string values.
modestringshiftDetermines how the mask input operates. Options are shift, replace and select.
prefixstringnoneCharacters that will always appear at the beginning of the input.
reversebooleanfalseRuns the mask in reverse — from right to left.
show-maskbooleantrueDisplays a live representation of the pattern’s placeholder as the internal value of the input.
suffixstringnoneCharacters that will always appear at the end of the input.
tokensObject{}Add new tokens or modify existing ones.
unmask-valuebooleanfalseBy default, the value of the input is the same as what is displayed (with formatting). The string literals will removed from the value if this prop is set to true.
Show universal props
configObject{}Configuration options to provide to the input’s node and any descendent node of this input.
delayNumber20Number of milliseconds to debounce an input’s value before the commit hook is dispatched.
errorsArray[]Array of strings to show as error messages on this field.
helpString''Text for help text associated with the input.
idStringinput_{n}The unique id of the input. Providing an id also allows the input’s node to be globally accessed.
ignoreBooleanfalsePrevents an input from being included in any parent (group, list, form etc). Useful when using inputs for UI instead of actual values.
indexNumberundefinedAllows an input to be inserted at the given index if the parent is a list. If the input’s value is undefined, it inherits the value from that index position. If it has a value it inserts it into the lists’s values at the given index.
labelString''Text for the label element associated with the input.
nameStringinput_{n}The name of the input as identified in the data object. This should be unique within a group of fields.
parentFormKitNodecontextualBy default the parent is a wrapping group, list or form — but this props allows explicit assignment of the parent node.
prefix-iconString''Specifies an icon to put in the prefixIcon section.
preservebooleanfalsePreserves the value of the input on a parent group, list, or form when the input unmounts.
preserve-errorsbooleanfalseBy default errors set on inputs using setErrors are automatically cleared on input, setting this prop to true maintains the error until it is explicitly cleared.
sections-schemaObject{}An object of section keys and schema partial values, where each schema partial is applied to the respective section.
suffix-iconString''Specifies an icon to put in the suffixIcon section.
typeStringtextThe type of input to render from the library.
validationString, Array[]The validation rules to be applied to the input.
validation-visibilityStringblurDetermines when to show an input's failing validation rules. Valid values are blur, dirty, and live.
validation-labelString{label prop}Determines what label to use in validation error messages, by default it uses the label prop if available, otherwise it uses the name prop.
validation-rulesObject{}Additional custom validation rules to make available to the validation prop.
valueAnyundefinedSeeds the initial value of an input and/or its children. Not reactive. Can seed entire groups (forms) and lists..

Sections

You can target a specific section of an input using that section's "key", allowing you to modify that section's classes, HTML (via :sections-schema), or content (via slots). Read more about sections here.

    Enter a phone number
    📞
    Input field
    ❤️
    🚀
    Please enter your phone number.
    Phone number is required.
      Section-key Description
      outerThe outermost wrapping element.
      wrapperA wrapper around the label and input.
      labelThe label of the input.
      prefixHas no output by default, but allows content directly before an input element.
      prefixIconAn element for outputting an icon before the prefix section.
      innerA wrapper around the actual input element.
      suffixHas no output by default, but allows content directly after an input element.
      suffixIconAn element for outputting an icon after the suffix section.
      inputThe input element itself.
      helpThe element containing help text.
      messagesA wrapper around all the messages.
      messageThe element (or many elements) containing a message — most often validation and error messages.