# MaskInput
Package: @mantine/core
Import: import { MaskInput } from '@mantine/core';
Description: Input with mask pattern for formatted text entry

## Usage

`MaskInput` is an input with a fixed format, for example a phone number or a credit card.
The `mask` string defines the format, see [mask pattern syntax](#mask-pattern-syntax).
The component is built on top of the [useMask](https://alpha.mantine.dev/llms/hooks-use-mask.md) hook:

```tsx
import { MaskInput } from '@mantine/core';


function Demo() {
  return (
    <MaskInput
       variant="default" size="sm" radius="md" label="Input label" withAsterisk={false} description="Input description" error=""
      mask="(999) 999-9999"
      placeholder="(___) ___-____"
    />
  );
}
```


## MaskInput with uncontrolled forms

Set `name` to submit the displayed text, including mask characters. `defaultValue` takes the raw value:

```tsx
import { MaskInput } from '@mantine/core';

function Demo() {
  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);
        console.log(data.get('code'));
      }}
    >
      <MaskInput name="code" label="Code" mask="99-99" defaultValue="1234" />
      <button type="submit">Submit</button>
    </form>
  );
}
```

## Dynamic mask

Use the `modify` option to change the mask based on the current value, for example
to switch between standard and American Express credit card formats:

```tsx
import { MaskInput } from '@mantine/core';

function Demo() {
  return (
    <MaskInput
      label="Credit card"
      placeholder="____ ____ ____ ____"
      mask="9999 9999 9999 9999"
      modify={(value) => {
        if (/^3[47]/.test(value)) {
          return { mask: '9999 999999 99999' };
        }
        return undefined;
      }}
    />
  );
}
```


## Custom tokens

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

```tsx
import { MaskInput } from '@mantine/core';

function Demo() {
  return (
    <MaskInput
      label="Hex color"
      placeholder="#______"
      mask="\\#hhhhhh"
      tokens={{ h: /[0-9a-fA-F]/ }}
    />
  );
}
```


## Regex array format

When built-in tokens are not enough, pass an array of string literals and `RegExp` objects:

```tsx
import { MaskInput } from '@mantine/core';

function Demo() {
  return (
    <MaskInput
      label="Time (HH:MM)"
      placeholder="__:__"
      mask={[/[0-2]/, /\\d/, ':', /[0-5]/, /\\d/]}
    />
  );
}
```


## Transform

Use the `transform` option to convert each character before validation, for example
to uppercase letters so that the `A` token accepts lowercase input:

```tsx
import { MaskInput, Text } from '@mantine/core';

function Demo() {
  return (
    <>
      <MaskInput
        label="Promo code"
        placeholder="AAA-9999"
        mask="AAA-9999"
        transform={(char) => char.toUpperCase()}
        slotChar="XXX-0000"
      />
      <Text size="sm" mt="sm">
        Type lowercase letters – they will be auto-uppercased
      </Text>
    </>
  );
}
```


## Disabled state

```tsx
import { MaskInput } from '@mantine/core';

function Demo() {
  return (
    <MaskInput
      label="Phone number"
      placeholder="(___) ___-____"
      mask="(999) 999-9999"
      disabled
    />
  );
}
```


## Error state

```tsx
import { MaskInput } from '@mantine/core';

function Demo() {
  return (
    <MaskInput
      label="Phone number"
      placeholder="(___) ___-____"
      mask="(999) 999-9999"
      error="Invalid phone number"
    />
  );
}
```


## Success state

```tsx
import { MaskInput } from '@mantine/core';

function Demo() {
  return (
    <MaskInput
      label="Phone number"
      placeholder="(___) ___-____"
      mask="(999) 999-9999"
      success="Looks good!"
    />
  );
}
```


## Controlled

`value`, `defaultValue` and `onChange` work with the raw value without the mask, for example
`1234567890` for `(123) 456-7890`. Use `onChangeRaw` to get both raw and masked values:

```tsx
import { useState } from 'react';
import { MaskInput } from '@mantine/core';

function Demo() {
  const [value, setValue] = useState('');

  return (
    <MaskInput
      mask="(999) 999-9999"
      value={value}
      onChange={setValue}
      onChangeRaw={(raw, masked) => console.log(raw, masked)}
      onComplete={(masked, raw) => console.log(masked, raw)}
    />
  );
}
```

## Reset value

To clear a controlled input, set `value` to an empty string.
In uncontrolled mode, use the `resetRef` prop to get a function that clears the input:

```tsx
import { useRef } from 'react';
import { MaskInput, Button, Group } from '@mantine/core';

function Demo() {
  const resetRef = useRef<() => void>(null);

  return (
    <>
      <MaskInput
        label="Phone number"
        placeholder="(___) ___-____"
        mask="(999) 999-9999"
        resetRef={resetRef}
      />

      <Group mt="md">
        <Button onClick={() => resetRef.current?.()}>Reset</Button>
      </Group>
    </>
  );
}
```


## With use-form

`MaskInput` works with [use-form](https://alpha.mantine.dev/llms/form-use-form.md) like any other input. The form receives
the raw value without the mask, for example `1234567890` for `(123) 456-7890`.
Values passed to `initialValues`, `form.setFieldValue` and `form.reset` must be raw values too:

```tsx
import { Button, MaskInput } from '@mantine/core';
import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    initialValues: { phone: '' },
  });

  return (
    <form onSubmit={form.onSubmit((values) => console.log(values))}>
      <MaskInput
        mask="(999) 999-9999"
        placeholder="(___) ___-____"
        label="Phone"
        {...form.getInputProps('phone')}
      />

      <Button type="submit" mt="md">
        Submit
      </Button>
    </form>
  );
}
```


## Mask pattern syntax

Each character of the mask string 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.
When the input is not focused, the empty optional part is hidden.
With `alwaysShowMask`, it stays visible with slot characters:

```tsx
<MaskInput mask="(999) 999-9999? x9999" /> // Extension is optional
```

### Escaping

Prefix a token character with `\` to treat it as a literal:

```tsx
<MaskInput mask="\A999" /> // "A" is literal, not a token
```


#### Props

**MaskInput props**

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| alwaysShowMask | boolean | - | Show mask pattern even when field is empty and unfocused |
| autoClear | boolean | - | Clear value on blur when mask is incomplete, `false` by default |
| defaultValue | string | - | Uncontrolled raw (unmasked) default value |
| description | React.ReactNode | - | Contents of `Input.Description` component. If not set, description is not displayed. |
| descriptionProps | InputDescriptionProps & DataAttributes & PlaceholderPolymorphicProps | - | Props passed down to the `Input.Description` component |
| disabled | boolean | - | Sets `disabled` attribute on the `input` element |
| error | React.ReactNode | - | Contents of `Input.Error` component. If not set, error is not displayed. |
| errorProps | InputErrorProps & DataAttributes & PlaceholderPolymorphicProps | - | Props passed down to the `Input.Error` component |
| inputContainer | (children: ReactNode) => ReactNode | (children) => children | Render function to wrap the input element. Useful for adding tooltips, popovers, or other wrappers around the input. |
| inputSize | string | - | HTML `size` attribute for the input element (number of visible characters) |
| inputWrapperOrder | ("input" \| "label" \| "description" \| "error")[] | ['label', 'description', 'input', 'error'] | Controls order and visibility of wrapper elements. Only elements included in this array will be rendered. |
| label | React.ReactNode | - | Contents of `Input.Label` component. If not set, label is not displayed. |
| labelProps | InputLabelProps & DataAttributes & PlaceholderPolymorphicProps | - | Props passed down to the `Input.Label` component |
| leftSection | React.ReactNode | - | Content section displayed on the left side of the input |
| leftSectionPointerEvents | React.CSSProperties["pointerEvents"] | 'none' | Sets `pointer-events` styles on the `leftSection` element. Use `'all'` when section contains interactive elements (buttons, links). |
| leftSectionProps | React.ComponentProps<"div"> | - | Props passed down to the `leftSection` element |
| leftSectionWidth | React.CSSProperties["width"] | - | Left section width, used to set `width` of the section and input `padding-left`, by default equals to the input height |
| loaderProps | LoaderProps | - | Props passed down to the `Loader` component displayed when `loading` prop is set |
| loading | boolean | false | Displays loading indicator in the left or right section |
| loadingPosition | "left" \| "right" | 'right' | Position of the loading indicator |
| mask | string \| (string \| RegExp)[] | required | Mask pattern string or array of string literals and RegExp objects |
| modify | ((value: string) => Partial<Pick<MaskInputProps, "mask" \| "tokens" \| "slotChar">>) \| undefined | - | Called with the raw (unmasked) value every time the mask state is computed, returns overrides for `mask`, `tokens` and `slotChar`. Must be a pure function. |
| onChange | (value: string) => void | - | Called with the raw (unmasked) value on every edit |
| onChangeRaw | (rawValue: string, maskedValue: string) => void | - | Called on every edit, the first argument is the raw (unmasked) value, the second is the masked value displayed in the input |
| onComplete | (maskedValue: string, rawValue: string) => void | - | Called when all required mask slots are filled, the first argument is the masked value, the second is the raw (unmasked) value |
| pointer | boolean | false | Determines whether the input should use the theme cursor type. Use when input acts as a button-like trigger (e.g., `component="button"` for Select/DatePicker). |
| radius | MantineRadius \| number | theme.defaultRadius | Key of `theme.radius` or any valid CSS value to set `border-radius`, numbers are converted to rem |
| required | boolean | false | Adds required attribute to the input and a red asterisk on the right side of label |
| resetRef | Ref<() => void> | - | Assigns a function that clears the input value to the given ref |
| rightSection | React.ReactNode | - | Content section displayed on the right side of the input |
| rightSectionPointerEvents | React.CSSProperties["pointerEvents"] | 'none' | Sets `pointer-events` styles on the `rightSection` element. Use `'all'` when section contains interactive elements (buttons, links). |
| rightSectionProps | React.ComponentProps<"div"> | - | Props passed down to the `rightSection` element |
| rightSectionWidth | React.CSSProperties["width"] | - | Right section width, used to set `width` of the section and input `padding-right`, by default equals to the input height |
| showMaskOnFocus | boolean | - | Show mask placeholder on focus, `true` by default |
| size | MantineSize | 'sm' | Controls input `height`, horizontal `padding`, and `font-size` |
| slotChar | string \| null | - | Character displayed in unfilled slots, `"_"` by default |
| success | React.ReactNode | - | Contents of `Input.Success` component. If not set, success is not displayed. |
| successProps | InputSuccessProps & DataAttributes & PlaceholderPolymorphicProps | - | Props passed down to the `Input.Success` component |
| tokens | Record<string, RegExp> | - | Override or extend the default token map |
| transform | (char: string) => string | - | Transform each character before validation and insertion |
| value | string | - | Controlled raw (unmasked) value |
| withAsterisk | boolean | false | If set, the required asterisk is displayed next to the label. Overrides `required` prop. Does not add required attribute to the input. |
| withErrorStyles | boolean | true | Determines whether the input should have red border and red text color when the `error` prop is set |
| withSuccessStyles | boolean | true | Determines whether the input should have green border when the `success` prop is set |
| wrapperProps | WrapperProps | - | Props passed down to the root element |


#### Styles API

MaskInput component supports Styles API. With Styles API, you can customize styles of any inner element. Follow the documentation to learn how to use CSS modules, CSS variables and inline styles to get full control over component styles.

**MaskInput selectors**

| Selector | Static selector | Description |
|----------|----------------|-------------|
| wrapper | .mantine-MaskInput-wrapper | Root element of the Input |
| input | .mantine-MaskInput-input | Input element |
| section | .mantine-MaskInput-section | Left and right sections |
| bottomSection | .mantine-MaskInput-bottomSection | Bottom section element, rendered inside the input border at the bottom |
| root | .mantine-MaskInput-root | Root element |
| childrenWrapper | .mantine-MaskInput-childrenWrapper | Container of `children`, rendered only when `withBlockChildren` prop is set |
| label | .mantine-MaskInput-label | Label element |
| required | .mantine-MaskInput-required | Required asterisk element, rendered inside label |
| description | .mantine-MaskInput-description | Description element |
| error | .mantine-MaskInput-error | Error element |
| success | .mantine-MaskInput-success | Success element |
