use-mask
Attach real-time input masking to any input element
Source
Package
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:
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:
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
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 hours is restricted to 0-2 and the first digit of minutes to 0-5:
Raw value:
Reset
Call reset to clear the input value:
Masked:
Raw:
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:
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:
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 focusedunformatMask(masked, options)– returns the raw value of a masked valueisMaskComplete(masked, options)– checks whether all required slots are filledgeneratePattern(mode, options)– generates a regex string for the HTMLpatternattribute
Definition
Exported types
UseMaskOptions and UseMaskReturnValue types are exported from the @mantine/hooks package: