Skip to content

createMask ​

Creates a mask from a pattern. A string or an array can be passed straight to mask and attach — createMask is for custom tokens, input preparation and a custom unmasked value.

Signature ​

ts
function createMask(options: MaskOptions | string | string[]): Mask

interface MaskOptions {
  pattern: string | string[] | ((input: string) => string);
  tokens?: Record<string, { pattern: RegExp; transform?: 'upper' | 'lower' | ((char: string) => string) }>;
  prepare?: (input: string) => string;
  allow?: (raw: string, char: string) => boolean;
  validate?: (result: MaskResult) => boolean;
  output?: (result: MaskResult) => string;
}
OptionDescription
patternA pattern, an array of patterns (the first fitting one is used) or a function of the input — see Patterns
tokensCustom tokens in addition to 9, a, *
prepareInput preparation before formatting — e.g. 8 → +7 at the start of a phone
allowWhether a character can be accepted given what's already typed (raw). That's how date masks reject day 32
validateWhether the filled value is correct — the result goes to valid and isValid. Called only when the mask is filled
outputThe unmasked value. Defaults to the typed characters without literals (result.raw)

MaskResult is { value, raw, complete, slots, overflow }: the formatted value, the typed characters, whether the mask is filled, positions of typed characters, whether extra characters were left.

Example ​

ts
// order number: 2 letters + 6 digits, stored without the dash
const orderNumber = createMask({
  pattern: 'LL-999999',
  tokens: { L: { pattern: /[a-z]/i, transform: 'upper' } },
});

mask('ab123456', orderNumber);   // 'AB-123456'
unmask('AB-123456', orderNumber); // 'AB123456'

See also ​