use-mask
Attach real-time input masking to any input element
Source
Docs
Package
Usage
use-mask hook adds input masking to any <input> element. It returns a ref that must be passed
to the input, the masked value and the raw unmasked value. If you need a ready-made input component,
use MaskInput.
Masked value:
Raw value:
isComplete, slotChar, and transform
isComplete–truewhen all required mask slots are filled, use it to enable a submit buttonslotChar– accepts a multi-character string to show a hint for each slottransform– converts each character before validation, the example uses it to uppercase the input
Raw value:
Dynamic mask
Use the modify option to change the mask based on the current input value.
This example switches between standard and American Express credit card formats:
Raw value:
Try starting with 34 or 37 for Amex format
Custom tokens
Override or extend the built-in token map with the tokens option:
Raw value:
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:
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 the time input is restricted to 0-2
and the first digit of minutes to 0-5:
Raw value:
Reset
Call reset function to clear the input value:
Masked:
Raw:
Mask pattern syntax
The mask string defines the expected format. Each character is either a token (editable slot) or a literal (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:
Utility functions
The following pure functions are exported alongside the hook:
formatMask(raw, options)– apply a mask to a raw value stringunformatMask(masked, options)– strip all mask literals from a masked valueisMaskComplete(masked, options)– check if all required slots are filledgeneratePattern(mode, options)– generate a regex string for HTMLpatternattribute
Definition
Exported types
The UseMaskOptions and UseMaskReturnValue types are exported from the @mantine/hooks package;
you can import them in your application: