# Input mask

A text field that formats what is typed into a fixed pattern: phone numbers, IBANs, plates, dates typed as digits. The caret stays where the user expects with every keyboard.

- Package: [@vigdx/ui](https://www.npmjs.com/package/@vigdx/ui)
- Selectors: `vig-input-mask`
- Source: [libs/ui/src/lib/molecules/input-mask/input-mask.ts](https://github.com/bakyurekk/vigdx/blob/main/libs/ui/src/lib/molecules/input-mask/input-mask.ts)

```typescript title="Import"
import { InputMask, MASK_DIGIT, MASK_LETTER, MASK_ALPHANUMERIC } from '@vigdx/ui/input-mask';
```

## Basic

Pass a `mask` pattern and bind `[(value)]`. Literals appear as the user types, Backspace skips over them, and the value holds the typed characters only (`5551234567`). In a pattern `9` is a digit, `a` a letter, `*` either, and `\` makes the next character literal. Escape token characters you mean literally: in `+90 (999)` the `9` is a slot, so write `+\90 (999)`. The keyboard follows the mask: digits only open the digit pad.

```typescript title="input-mask-basic.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { InputMask } from '@vigdx/ui/input-mask';

@Component({
  selector: 'app-input-mask-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [InputMask],
  template: `
    <div class="max-w-sm">
      <vig-input-mask
        label="Phone"
        mask="(999) 999-9999"
        autocomplete="tel-national"
        [(value)]="phone"
      />
    </div>
    <p class="text-sm text-muted-foreground">Value: "{{ phone() }}"</p>
  `,
})
export class InputMaskBasicDemo {
  protected readonly phone = signal('');
}
```

## Placeholder character, formatted value and completion

`placeholderChar="_"` shows the whole pattern while the field is focused or filled. `valueFormat="formatted"` makes the value the text as shown (`31/12/19`) instead of the raw characters. An incomplete value is kept, never cleared: validate it with the form. `(completed)` fires when the last slot is filled.

```typescript title="input-mask-patterns.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { InputMask, MASK_DIGIT, type Mask, type MaskSlot } from '@vigdx/ui/input-mask';

/** A letter slot that upper-cases what is typed. */
const LETTER: MaskSlot = {
  accepts: (char) => /^[a-z]$/i.test(char),
  transform: (char) => char.toUpperCase(),
};
const D = MASK_DIGIT;
/** A Turkish plate: two digits, one to three letters (three here), two to four digits. */
const PLATE: Mask = [D, D, ' ', LETTER, LETTER, LETTER, ' ', D, D, D];

@Component({
  selector: 'app-input-mask-patterns',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [InputMask],
  template: `
    <div class="grid gap-4 sm:grid-cols-2">
      <vig-input-mask
        label="Date of birth"
        mask="99/99/9999"
        placeholderChar="_"
        valueFormat="formatted"
        autocomplete="off"
        hint="DD/MM/YYYY"
        [(value)]="date"
      />
      <vig-input-mask
        label="Licence plate"
        [mask]="plateMask"
        placeholder="34 ABC 123"
        [(value)]="plate"
        (completed)="complete.set($event)"
      />
    </div>
    <p class="text-sm text-muted-foreground">
      Date: "{{ date() }}" · Plate: "{{ plate() }}"
      @if (complete()) {
        · completed with "{{ complete() }}"
      }
    </p>
  `,
})
export class InputMaskPatternsDemo {
  protected readonly plateMask = PLATE;
  protected readonly date = signal('');
  protected readonly plate = signal('');
  protected readonly complete = signal('');
}
```

## Custom slots

For anything a pattern cannot say, pass an array of literal strings and `MaskSlot` objects: `{ accepts: (char) => boolean, transform?, inputMode? }`. `MASK_DIGIT`, `MASK_LETTER` and `MASK_ALPHANUMERIC` are the pattern's slots. Here letters are upper-cased as they are typed.

```typescript title="input-mask-custom.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { InputMask, MASK_DIGIT, type Mask, type MaskSlot } from '@vigdx/ui/input-mask';

/** A letter slot that upper-cases what is typed. */
const LETTER: MaskSlot = {
  accepts: (char) => /^[a-z]$/i.test(char),
  transform: (char) => char.toUpperCase(),
};
const D = MASK_DIGIT;

/** A Turkish IBAN: TR, two check digits, 22 digits in groups of four. */
const IBAN: Mask = [
  LETTER,
  LETTER,
  D,
  D,
  ...[0, 1, 2, 3, 4].flatMap(() => [' ', D, D, D, D]),
  ' ',
  D,
  D,
];

@Component({
  selector: 'app-input-mask-custom',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [InputMask],
  template: `
    <div class="max-w-md">
      <vig-input-mask label="IBAN" [mask]="iban" autocomplete="off" [(value)]="value" />
    </div>
    <p class="text-sm text-muted-foreground">Value: "{{ value() }}"</p>
  `,
})
export class InputMaskCustomDemo {
  protected readonly iban = IBAN;
  protected readonly value = signal('');
}
```

## Icons, label position, states and sizes

The `vigInputPrefix` and `vigInputSuffix` slots of `vig-input` work here too. `labelPosition`, `hideLabel`, `disabled`, `readonly` and `size` behave as in the other text fields.

```typescript title="input-mask-states.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Icon } from '@vigdx/ui/icon';
import { InputPrefix } from '@vigdx/ui/input-field';
import { InputMask } from '@vigdx/ui/input-mask';

@Component({
  selector: 'app-input-mask-states',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Icon, InputMask, InputPrefix],
  template: `
    <div class="grid gap-4 sm:grid-cols-2">
      <vig-input-mask label="Search by code" mask="aa-9999">
        <vig-icon vigInputPrefix name="search" />
      </vig-input-mask>
      <vig-input-mask label="Label on top" labelPosition="top" mask="9999" placeholder="0000" />
      <vig-input-mask label="Disabled" mask="(999) 999-9999" value="5551234567" disabled />
      <vig-input-mask label="Read-only" mask="(999) 999-9999" value="5551234567" readonly />
      <vig-input-mask label="Small" size="sm" mask="999-999" />
      <vig-input-mask label="Large" size="lg" mask="999-999" />
    </div>
  `,
})
export class InputMaskStatesDemo {}
```

## Signal Forms

`vig-input-mask` implements `FormValueControl<string>` for `[formField]`. With the raw value, a complete phone number is 10 characters long, so `minLength` checks completeness. A value set from outside may be raw or formatted (`+1 (555) 123-4567` is read through its literals); it is written back in the field's own form, which leaves Reactive Forms and `ngModel` controls pristine but makes a Signal Forms field dirty.

```typescript title="input-mask-signal-forms.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { FormField, form, minLength, required } from '@angular/forms/signals';
import { InputMask } from '@vigdx/ui/input-mask';

@Component({
  selector: 'app-input-mask-signal-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormField, InputMask],
  template: `
    <div class="max-w-sm">
      <vig-input-mask label="Phone" mask="(999) 999-9999" [formField]="contact.phone" />
    </div>
    <p class="text-sm text-muted-foreground">Valid: {{ contact().valid() ? 'yes' : 'no' }}</p>
  `,
})
export class InputMaskSignalFormsDemo {
  protected readonly model = signal({ phone: '' });
  protected readonly contact = form(this.model, (path) => {
    required(path.phone);
    // The raw value holds the digits only: 10 of them make a complete number.
    minLength(path.phone, 10, { message: 'Enter all 10 digits.' });
  });
}
```

## Reactive Forms

Import `VigValueAccessor` next to the component to use `formControlName`, `[formControl]` or `ngModel`.

```typescript title="input-mask-reactive-forms.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { VigValueAccessor } from '@vigdx/ui/core';
import { InputMask } from '@vigdx/ui/input-mask';

@Component({
  selector: 'app-input-mask-reactive-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ReactiveFormsModule, InputMask, VigValueAccessor],
  template: `
    <div class="max-w-sm">
      <vig-input-mask
        label="Postal code"
        mask="99999"
        autocomplete="postal-code"
        [formControl]="postalCode"
      />
    </div>
    <p class="text-sm text-muted-foreground">Value: "{{ value() }}"</p>
  `,
})
export class InputMaskReactiveFormsDemo {
  protected readonly postalCode = new FormControl('34000', {
    nonNullable: true,
    validators: [Validators.required, Validators.minLength(5)],
  });
  protected readonly value = toSignal(this.postalCode.valueChanges, {
    initialValue: this.postalCode.value,
  });
}
```

## How editing works

- Every edit is read from the `beforeinput` event, applied to the mask and written back with the caret in place, so nothing jumps in Chromium, Firefox or WebKit. Edits a browser does not let the field cancel (some Android keyboards, word deletions, cut, spell-check and autofill) are read back from the `input` event instead.
- Typing in the middle moves the following characters along; deleting moves them back. Backspace and Delete skip over literals to the nearest character. A full mask refuses more characters instead of dropping the last one.
- Paste and drop take formatted text (`(555) 123-4567`) or plain characters, and drop whatever overflows. Autofill fills the whole value.
- IME compositions (Japanese, Chinese, Korean keyboards; Android word suggestions) are left alone until they end, then applied; full-width and Arabic-Indic digits become ASCII.
- Undo and redo (Ctrl+Z, Ctrl+Shift+Z or Ctrl+Y; ⌘Z and ⇧⌘Z on Apple devices, on any keyboard layout) step through the field's own history, and fire `(completed)` when they bring back a complete value. The browser's Edit menu and shake to undo do not reach it: the field rewrites every edit, which the browser's own undo history does not record.
- In masks that mix letters and digits, an edit that would move characters into slots that reject them is refused: typing `0` before `34A` in `99 aaa 999` does nothing, and deleting a letter of `aa99` selects it instead, so typing replaces it. Nothing after the caret is ever lost; select text to type over it.
- A character the mask rejects, typed or pasted over a selection, leaves the selection as it is. Cut and drag remove exactly what they select, literals included, without taking a character next to them.

## Styling hooks

Internal elements carry a stable `data-part` and the component's `data-scope`; both are public API, so removing one is a breaking change. Select a part by both, e.g. `[data-scope="input-mask"][data-part="field"] { … }`: the pair stays within this component when kit components nest, and also reaches parts in overlay panels, which render outside the host. State is exposed through `aria-*` and, where listed, a `data-state`; literal values are checked by the API gate, values computed from the component's state follow its documented types. Other `data-*` attributes listed below (such as `data-opening` while an overlay animates) are API too. See [Customizing](https://vigdx.com/docs/theming.md#customizing).

Scope: `[data-scope="input-mask"]`

| Part | Element | data-state |
| --- | --- | --- |
| `field` | Positioned wrapper of the label, slots and control. |   |
| `label` | The visible (or floating) label. |   |
| `prefix` | Wrapper of the `[vigInputPrefix]` slot. |   |
| `input` | The native `<input>` (always `dir="ltr"`). |   |
| `suffix` | Wrapper of the `[vigInputSuffix]` slot. |   |
| `hint` | The `vig-hint` (a `display: contents` host; style its `text` part). |   |
| `disabled-reason` | The `vig-hint` with the disabled reason (`display: contents`). |   |
| `error` | The `vig-field-error` (a `display: contents` host; style its `message` part). |   |

## Accessibility

- A native `<input type="text">` named by a real `<label>`; hint, disabled reason and error are linked through `aria-describedby`. Describe the expected format in the `hint` or a `placeholder` example: screen readers read the value, not the pattern.
- `inputmode` follows the mask, and autocorrect, auto-capitalization and spell check are off. Set `autocomplete` (`tel-national`, `postal-code`, `cc-number`…) so browsers can fill the field (WCAG 1.3.5).
- The text always runs left to right (`dir="ltr"`), also on RTL pages, so phone numbers and codes keep their order; it aligns to the page's start, where the label and prefix sit.

## API

### InputMask

Selector: `vig-input-mask` · Kind: component

A text field that formats what is typed into a fixed pattern — phone numbers, IBANs, codes, dates typed as digits:

**Example :**

```html
<vig-input-mask label="Phone" mask="(999) 999-9999" autocomplete="tel-national" [(value)]="phone" />
```

In a pattern `9` is a digit, `a` a letter, `*` either and `\` escapes a literal; pass an array of literals and `MaskSlot`s for custom slots. The value is the typed characters only (`5551234567`); `valueFormat="formatted"` makes it the text as shown. An incomplete value is kept, never cleared: validate it with the form (`(completed)` fires once every slot is filled).

Editing goes through `beforeinput` (cancelled and applied by the field) and falls back to reading the `input` event's change, so mobile keyboards, IME compositions, paste, drop, autofill and undo all keep the caret in place. The text always runs left to right (`dir="ltr"`), also on RTL pages.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `autocomplete` | `string \| undefined` | `undefined` | Native `autocomplete`, e.g. `tel-national` or `postal-code`, so autofill can help. |
| `dirty` | `boolean` | `false` | — |
| `disabled` | `boolean` | `false` | — |
| `disabledReasons` | `readonly WithOptionalFieldTree<DisabledReason>[]` | `[]` | — |
| `errorMessages` | `Record<string, string>` | — | — |
| `errors` | `readonly ValidationError.WithOptionalFieldTree[]` | `[]` | — |
| `hidden` | `boolean` | `false` | — |
| `hideLabel` | `boolean` | `false` | Visually hides the label, which still names the field; pair it with a placeholder. |
| `hint` | `string \| undefined` | `undefined` | — |
| `invalid` | `boolean` | `false` | — |
| `label` (required) | `string` | — | — |
| `labelPosition` | `LabelPosition` | `'float'` | `float` (default) rests the label inside the field; `top` sets it above. |
| `mask` (required) | `Mask` | — | The pattern (`'(999) 999-9999'`) or an array of literals and `MaskSlot`s. |
| `name` | `string` | `''` | — |
| `pending` | `boolean` | `false` | — |
| `placeholder` | `string \| undefined` | `undefined` | Native placeholder of the empty field, e.g. an example value. |
| `placeholderChar` | `string \| undefined` | `undefined` | Shows the whole pattern while the field is focused or filled, with this character in the empty slots (e.g. `_`). Unset, the text grows as the user types. |
| `readonly` | `boolean` | `false` | — |
| `required` | `boolean` | `false` | — |
| `size` | `FieldSize` | `'md'` | — |
| `touched` | `boolean` | `false` | — |
| `value` (model) | `string` | `''` | — |
| `valueFormat` | `InputMaskValueFormat` | `'raw'` | `raw` (default): the value holds the typed characters only (`5551234567`). `formatted`: the text as shown, up to the last typed character (`(555) 123`). |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `completed` | `string` | Emits the value when the user fills the last empty slot. |
| `touch` | `void` | — |
| `valueChange` | `string` | — |

#### Methods

| Signature | Description |
| --- | --- |
| `focus(options?: FocusOptions): void` | Moves focus to the control's interactive element (the input, or the trigger of a popup control). Signal Forms calls it through `field().focusBoundControl()`; the host element itself cannot take focus. |
| `reset(): void` | Drops the undo history; see `VigFormField.reset`. |

### VigValueAccessor

Kind: directive

Bridges the vigdx form fields to Reactive Forms (`formControl`, `formControlName`) and template-driven forms (`ngModel`). Import it next to the component; Signal Forms (`[formField]`) need no accessor.

#### Methods

| Signature | Description |
| --- | --- |
| `registerOnChange(fn: (value: unknown) => void): void` | — |
| `registerOnTouched(fn: () => void): void` | — |
| `setDisabledState(disabled: boolean): void` | — |
| `writeValue(value: unknown): void` | — |
