Mask expression

Mask expression is the the main concept of Maskito core library. It provides the developer with opportunity to predefine format of user's input. For example, you can set mask expression to accept only digits, only Latin letters or you can configure more complex patterns like a date string.

You can set mask expression using mask parameter of MaskitoOptions .

Types of mask expression

  • RegExp mask expression

    The most basic and comprehensible type. The only required knowledge is understanding of native JavaScript Regular expression .

    See the following example:

    Make sure that mask expression works with any of intermediate states, not just the final value.

    For example, imagine that you have to create mask for 4-digits PIN code.

    /^\d{4}$/ is a wrong mask expression. It does not match intermediate states (you cannot complete 4-digit string without possibility to type 1-, 2- or 3-digit string).

    /^\d{0,4}$/ is the right solution for our example.

  • Pattern mask expression

    It is a good choice for more complex masks that are fixed in size. This type of mask expression is presented as array. Each element in the array has to be either a string or a regular expression. Each string is a fixed character and each regular expression is validator of character at the same index.

    Fixed character — a predefined character at a certain position (the same as its index inside mask expression array). It is automatically added when user forgets to type it. It cannot be erased or replaced with another character.

    For example, imagine that you have to create mask for a time-string with HH:MM format. It consists of 4 digits and 1 fixed-character separator : .


    This mask expression forbids anything excepts digits and limits length of the value to 5 characters.

    Also, it manages user interactions with fixed character.

    For example, user can just type four digits 1159 and the value becomes 11:59

    Another example, if caret position is after the colon and user presses Backspace , the input's value will not change but caret will be moved to the left of the colon.

  • Dynamic mask expression

    mask parameter can also accepts function which generates mask expression. This function will be called every time before input changes to generate a new version of mask expression.

    An "Element state" object with raw value and current selection is passed as an argument to the function.
    Be careful! It can be not performance-friendly to generate new mask expression on every input change.

    Think about optimization and memoization of the such function.

Next steps

The following sections are recommended to explore core concepts further: