use-mask

Attach real-time input masking to any input element

Usage

use-mask adds input masking to any <input> element. It returns a ref for the input, the masked value and the raw unmasked value. If you need a ready-made input, use MaskInput:

Masked value:

Raw value:

import { TextInput, Text } from '@mantine/core';
import { useMask } from '@mantine/hooks';

function Demo() {
  const { ref, value, rawValue } = useMask({ mask: '(999) 999-9999' });

  return (
    <>
      <TextInput ref={ref} label="Phone number" placeholder="(___) ___-____" />
      <Text size="sm" mt="sm">Masked value: {value}</Text>
      <Text size="sm">Raw value: {rawValue}</Text>
    </>
  );
}

Complete state and transform

isComplete is true when all required slots are filled, use it to enable a submit button. slotChar sets the placeholder of empty slots, a multi-character string shows a hint for each slot. transform converts each character before validation, the example uppercases the input:

Raw value:

import { Button, Group, Text, TextInput } from '@mantine/core';
import { useMask } from '@mantine/hooks';

function Demo() {
  const { ref, isComplete, rawValue } = useMask({
    mask: 'AAA-9999',
    slotChar: 'XXX-0000',
    transform: (char) => char.toUpperCase(),
  });

  return (
    <>
      <TextInput ref={ref} label="Promo code" placeholder="Enter promo code" />
      <Text size="sm" mt="sm">Raw value: {rawValue}</Text>
      <Group mt="xs">
        <Button disabled={!isComplete} size="xs">Apply code</Button>
      </Group>
    </>
  );
}

Dynamic mask

Use the modify option to change the mask based on the current value. This example switches between standard and American Express card formats. generatePattern always uses the base mask:

Raw value:

Try starting with 34 or 37 for Amex format

import { TextInput, Text } from '@mantine/core';
import { useMask } from '@mantine/hooks';

function Demo() {
  const { ref, rawValue } = useMask({
    mask: '9999 9999 9999 9999',
    modify: (value) => {
      const digits = value.replace(/\D/g, '');
      if (digits.startsWith('34') || digits.startsWith('37')) {
        return { mask: '9999 999999 99999' };
      }
    },
  });

  return (
    <>
      <TextInput ref={ref} label="Credit card number" placeholder="Enter card number" />
      <Text size="sm" mt="sm">Raw value: {rawValue}</Text>
      <Text size="sm">Try starting with 34 or 37 for Amex format</Text>
    </>
  );
}

Custom tokens

Override or extend the built-in token map with the tokens option:

Raw value:

import { TextInput, Text } from '@mantine/core';
import { useMask } from '@mantine/hooks';

function Demo() {
  const { ref, rawValue } = useMask({
    mask: '\\#hhhhhh',
    tokens: { h: /[0-9a-fA-F]/ },
  });

  return (
    <>
      <TextInput ref={ref} label="Hex color" placeholder="#______" />
      <Text size="sm" mt="sm">Raw value: {rawValue}</Text>
    </>
  );
}

Escaping

Prefix a token character with \ to treat it as a literal. In this example, \A is a literal character, not an uppercase letter token:

Raw value:

import { TextInput, Text } from '@mantine/core';
import { useMask } from '@mantine/hooks';

function Demo() {
  const { ref, rawValue } = useMask({
    mask: '\\A-9999',
  });

  return (
    <>
      <TextInput ref={ref} label="Product code" placeholder="A-____" />
      <Text size="sm" mt="sm">Raw value: {rawValue}</Text>
    </>
  );
}

Regex array format

If built-in tokens are not enough, pass an array of string literals and RegExp objects. In this example, the first digit of hours is restricted to 0-2 and the first digit of minutes to 0-5:

Raw value:

import { TextInput, Text } from '@mantine/core';
import { useMask } from '@mantine/hooks';

function Demo() {
  const { ref, rawValue } = useMask({
    mask: [/[0-2]/, /\d/, ':', /[0-5]/, /\d/],
  });

  return (
    <>
      <TextInput ref={ref} label="Time (HH:MM)" placeholder="__:__" />
      <Text size="sm" mt="sm">Raw value: {rawValue}</Text>
    </>
  );
}

Reset

Call reset to clear the input value:

Masked:

Raw:

import { Button, Group, Text, TextInput } from '@mantine/core';
import { useMask } from '@mantine/hooks';

function Demo() {
  const { ref, value, rawValue, reset } = useMask({
    mask: '(999) 999-9999',
  });

  return (
    <>
      <TextInput ref={ref} label="Phone number" placeholder="(___) ___-____" />
      <Text size="sm" mt="sm">Masked: {value}</Text>
      <Text size="sm">Raw: {rawValue}</Text>
      <Group mt="xs">
        <Button size="xs" variant="default" onClick={reset}>Reset</Button>
      </Group>
    </>
  );
}

Set value

Call setValue with a raw value to replace the input value, for example 1234567890 for (123) 456-7890. onChangeRaw and onComplete are not called:

import { useMask } from '@mantine/hooks';

function Demo() {
  const { ref, setValue } = useMask({ mask: '(999) 999-9999' });

  return (
    <>
      <input ref={ref} />
      <button type="button" onClick={() => setValue('1234567890')}>
        Set value
      </button>
    </>
  );
}

Mask pattern syntax

Each character of the mask is either a token (an editable slot) or a literal (a fixed character inserted automatically).

Built-in tokens

  • 9 – any single digit ([0-9])
  • a – any single letter ([A-Za-z])
  • A – any uppercase letter ([A-Z])
  • * – any alphanumeric character ([A-Za-z0-9])
  • # – digit or sign ([-+0-9])

Optional segments

Append ? after the last required character to mark remaining slots as optional. The empty optional part is dropped from the value passed to onComplete and from the value shown when the input is not focused. With alwaysShowMask, it stays visible with slot characters:

useMask({ mask: '(999) 999-9999? x9999' }) // Extension is optional

Utility functions

The following functions are exported from @mantine/hooks:

  • formatMask(raw, options) – formats a raw value the way the input shows it when not focused
  • unformatMask(masked, options) – returns the raw value of a masked value
  • isMaskComplete(masked, options) – checks whether all required slots are filled
  • generatePattern(mode, options) – generates a regex string for the HTML pattern attribute
import { formatMask, unformatMask, isMaskComplete } from '@mantine/hooks';

const options = { mask: '(999) 999-9999' };

formatMask('1234567890', options);      // "(123) 456-7890"
unformatMask('(123) 456-7890', options); // "1234567890"
isMaskComplete('(123) 456-7890', options); // true

Definition

interface UseMaskOptions {
  // Mask pattern string or array of string literals and RegExp objects
  mask: string | Array<string | RegExp>;

  // Override or extend the default token map
  tokens?: Record<string, RegExp>;

  // Called with the raw value every time the mask state is computed, returns overrides
  // for mask, tokens or slotChar, must be a pure function
  modify?: (value: string) => Partial<Pick<UseMaskOptions, 'mask' | 'tokens' | 'slotChar'>> | undefined;

  // Transform each character before validation and insertion
  transform?: (char: string) => string;

  // Character displayed in unfilled slots, "_" by default
  slotChar?: string | null;

  // Show mask pattern even when the field is empty and unfocused
  alwaysShowMask?: boolean;

  // Show mask placeholder on focus, true by default
  showMaskOnFocus?: boolean;

  // Clear value on blur when mask is incomplete, false by default
  autoClear?: boolean;

  // Sets aria-invalid on the input, the attribute is not changed when the option is not set
  invalid?: boolean;

  // Called on every edit with the raw value first and the masked value second
  onChangeRaw?: (rawValue: string, maskedValue: string) => void;

  // Called when all required mask slots are filled, with the masked value first and the raw value second
  onComplete?: (maskedValue: string, rawValue: string) => void;
}

interface UseMaskReturnValue {
  // Ref callback to attach to the input element
  ref: React.RefCallback<HTMLInputElement>;

  // Current masked display value
  value: string;

  // Current raw unmasked value
  rawValue: string;

  // Whether all required mask slots are filled
  isComplete: boolean;

  // Clear the input value and reset state
  reset: () => void;

  // Sets the raw value and applies the mask to it, does not call onChangeRaw and onComplete
  setValue: (value: string) => void;
}

function useMask(options: UseMaskOptions): UseMaskReturnValue;

Exported types

UseMaskOptions and UseMaskReturnValue types are exported from the @mantine/hooks package:

import type { UseMaskOptions, UseMaskReturnValue } from '@mantine/hooks';