# MaskedField

> A text input with an input mask from @salmonui/inputs/masked-field, with raw and masked values, custom tokens and form submission.

Canonical: https://salmonui.dev/docs/inputs/masked-field

`MaskedField` is a text input with an input mask. The visible native input
shows the masked text; the value is the raw text (entered characters only),
and a hidden input with `name` submits the raw or masked value.

```tsx
import { formatMasked, MaskedField } from '@salmonui/inputs/masked-field';
import '@salmonui/inputs/masked-field/styles.css';

<MaskedField name="phone" label="Phone" mask="(000) 000-0000" description="(555) 123-4567" />
formatMasked('(000) 000-0000', '5551234567'); // '(555) 123-4567'
```

### Live demo: MaskedField basics

Live demo: https://salmonui.dev/demos/inputs/masked-field-basics

A phone mask with raw and masked values, an upper-cased product code and a time mask with character classes.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { MaskedField } from '@salmonui/inputs/masked-field';

// A phone mask with raw and masked values, a case-shifted code and custom tokens.
export default function MaskedFieldBasicsDemo() {
  const [raw, setRaw] = useState('');
  const [masked, setMasked] = useState('');
  return (
    <div style={{ display: 'grid', gap: 16, maxWidth: 360 }}>
      <MaskedField
        label="Phone"
        mask="(000) 000-0000"
        description="For example (555) 123-4567"
        value={raw}
        onValueChange={(value, details) => {
          setRaw(value);
          setMasked(details.masked);
        }}
        clearable
      />
      <output>
        Raw: {JSON.stringify(raw)} · Masked: {JSON.stringify(masked)}
      </output>
      <MaskedField label="Product code" mask=">LL-0000" placeholder="AB-1234" />
      <MaskedField label="Time" mask="[0-2]0:[0-5]0" placeholderChar="•" description="24-hour clock, for example 09:30" />
    </div>
  );
}
```

## Mask syntax

Mask elements. An empty mask is a plain text field.

| Element | Accepts |
| --- | --- |
| `0` | a digit (required) |
| `9` | a digit or space (optional) |
| `#` | a digit, space, `+` or `-` (optional) |
| `L` / `?` | a letter (required / optional) |
| `&` / `C` | any non-space character (required) / any character (optional) |
| `A` / `a` | a letter or digit (required / optional) |
| `>` / `<` / `\|` | upper-case / lower-case what follows / stop shifting |
| `\x` | the literal `x` |
| `[0-2]` | one character of the class |
| `tokens` | custom characters: `{ '#': '+-' }` (allowed characters) or `{ P: /[A-Z]/ }` |

`placeholderChar` (default `_`) fills empty positions. The masked text appears when the field is focused or has a
value; otherwise the native `placeholder` shows.

## Value

`value` with `onValueChange` makes the field controlled, `defaultValue`
uncontrolled (restored by a form reset). `value` / `defaultValue` are raw;
`onValueChange(raw, details)` carries
`details.masked`, `details.complete` and `reason` (`'input' | 'paste' |
'delete' | 'clear' | 'reset'`). `formatMasked(mask, raw, { tokens,
placeholderChar })` is the pure masked text; `parseMask` compiles a mask once.

`submitValue: 'raw' | 'masked'` (default `'raw'`) picks what the hidden
named input submits.

### Live demo: Fields in a form

Live demo: https://salmonui.dev/demos/inputs/field-forms

Uncontrolled text, masked, number, radio, checkbox, switch, range slider, rating and signature fields in a native form - names and values submitted through FormData, a required incomplete mask blocking the submit, and a form reset restoring every default.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Form } from '@salmonui/inputs/form';
import { MaskedField } from '@salmonui/inputs/masked-field';
import { NumberField } from '@salmonui/inputs/number-field';
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';
import { Rating } from '@salmonui/inputs/rating';
import { Select } from '@salmonui/dropdowns/select';
import { SignaturePad } from '@salmonui/inputs/signature-pad';
import { Slider } from '@salmonui/inputs/slider';
import { Switch } from '@salmonui/inputs/switch';
import { TextField } from '@salmonui/inputs/text-field';

/** One line per FormData entry; long data URLs are shortened. */
function entriesOf(form: HTMLFormElement): string[] {
  return Array.from(new FormData(form), ([key, value]) => {
    const text = typeof value === 'string' ? value : `File ${value.name}`;
    return `${key} = ${text.length > 48 ? `${text.slice(0, 40)}… (${text.length} chars)` : JSON.stringify(text)}`;
  });
}

// Every field is uncontrolled inside a native form: names submit through
// FormData (custom-drawn controls through native or hidden inputs) and the
// Reset button restores each defaultValue and clears the shown errors.
export default function FieldFormsDemo() {
  const [submitValue, setSubmitValue] = useState<'raw' | 'masked'>('raw');
  const [entries, setEntries] = useState<readonly string[]>([]);
  const [status, setStatus] = useState('Change some fields, then submit or reset.');
  return (
    <>
      <div className="demo-toolbar">
        <label>
          MaskedField submitValue
          <Select aria-label="MaskedField submitValue" data={['raw', 'masked']} value={submitValue} onValueChange={(value) => value != null && setSubmitValue(value as 'raw' | 'masked')} />
        </label>
      </div>
      <Form
        aria-label="Delivery preferences"
        style={{ display: 'grid', gap: 16, maxInlineSize: 420 }}
        onSubmit={(event) => {
          event.preventDefault();
          setEntries(entriesOf(event.currentTarget));
          setStatus('Submitted: the FormData entries are listed below.');
        }}
        onValidate={({ valid }) => !valid && setStatus('Not submitted: fix the highlighted field.')}
        onReset={() => {
          setEntries([]);
          setStatus('Reset: every field is back to its defaultValue.');
        }}
      >
        <TextField name="name" label="Name" defaultValue="Ada Lovelace" required />
        <MaskedField name="phone" label="Phone" mask="(000) 000-0000" defaultValue="5551234567" required submitValue={submitValue} description="Required: an incomplete number blocks the submit" />
        <NumberField name="parcels" label="Parcels" defaultValue={2} min={1} max={9} />
        <RadioGroup name="slot" label="Delivery slot" defaultValue="am" orientation="horizontal">
          <Radio value="am">Morning</Radio>
          <Radio value="pm">Afternoon</Radio>
        </RadioGroup>
        <Checkbox name="extras" value="gift-wrap" defaultChecked>
          Gift wrap
        </Checkbox>
        <Switch name="notify" value="sms">
          Text me when it ships
        </Switch>
        <Slider name="window" label="Delivery window (hours)" defaultValue={[9, 17]} min={6} max={22} ticks={{ placement: 'after', majorStep: 4 }} />
        <Rating name="priority" label="Priority" defaultValue={2} count={3} />
        <SignaturePad name="signature" label="Signature" description="Optional: submitted as a PNG data URL" height={120} backgroundColor="#ffffff" />
        <div style={{ display: 'flex', gap: 8 }}>
          <Button type="submit" tone="primary">
            Submit
          </Button>
          <Button type="reset" variant="outline">
            Reset
          </Button>
        </div>
      </Form>
      <p className="demo-status" role="status">
        {status}
      </p>
      <pre className="demo-log" aria-label="Submitted FormData">
        {entries.length === 0 ? '(nothing submitted yet)' : entries.join('\n')}
      </pre>
    </>
  );
}
```

## Editing

Edits go through `beforeinput`: typing fills the next accepting
position and skips literals; Backspace and Delete clear the previous or next
position without shifting the rest; a selection is cleared first; pasted text
is masked character by character. During IME composition the mask pauses
and applies the composed text on `compositionend`.

### Live demo: Mask tokens and editing

Live demo: https://salmonui.dev/demos/inputs/masked-field-tokens

MaskedField custom tokens from a RegExp and from a string of allowed characters, details.masked and formatMasked, and the caret rules for typing, deleting and pasting.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { formatMasked, MaskedField, type MaskTokens } from '@salmonui/inputs/masked-field';
import { TextField } from '@salmonui/inputs/text-field';

// Custom mask characters: `H` takes one hex digit, `#` stays a literal.
const HEX: MaskTokens = { H: /[0-9a-fA-F]/ };
// A string token lists the allowed characters: `D` is a direction letter.
const GRID: MaskTokens = { D: 'NSEW' };

// Custom tokens, the masked value from details and formatMasked, and the
// caret rules for typing, deleting over literals and pasting.
export default function MaskedFieldTokensDemo() {
  const [color, setColor] = useState('1e90ff');
  const [masked, setMasked] = useState('#1e90ff');
  const [last, setLast] = useState('none');
  const [raw, setRaw] = useState('4155550123');
  return (
    <div style={{ display: 'grid', gap: 16, maxInlineSize: 380 }}>
      <MaskedField
        label="Brand color"
        mask="\#HHHHHH"
        tokens={HEX}
        value={color}
        onValueChange={(value, details) => {
          setColor(value);
          setMasked(details.masked);
          setLast(`${details.reason} (${details.source}), complete: ${details.complete}`);
        }}
        startAdornment={<span aria-hidden="true" style={{ display: 'inline-block', inlineSize: 16, blockSize: 16, borderRadius: 'var(--salmon-radius-sm)', background: color.length === 6 ? `#${color}` : 'transparent', border: '1px solid currentColor' }} />}
        description="Token H accepts 0-9 and a-f"
      />
      <output>
        Raw {JSON.stringify(color)} · details.masked {JSON.stringify(masked)} · last change: {last}
      </output>
      <MaskedField label="Grid reference" mask=">D00-D00" tokens={GRID} description="Token D accepts N, S, E or W (typed letters are upper-cased)" />
      <MaskedField label="Phone" mask="+1 (000) 000-0000" description="Paste 4155550123 or (415) 555-0123; Backspace clears the previous digit without shifting the rest" />
      <TextField label="Raw value for formatMasked()" value={raw} onValueChange={(value) => setRaw(value)} />
      <output>
        formatMasked(&apos;+1 (000) 000-0000&apos;, raw) = <span style={{ whiteSpace: 'nowrap' }}>{JSON.stringify(formatMasked('+1 (000) 000-0000', raw))}</span>
      </output>
    </div>
  );
}
```

A value with empty required positions is invalid with
`localeText.incomplete` ("Please complete the value.");
`required` makes an empty field invalid too.

## Keyboard and screen readers

| Key | Action |
| --- | --- |
| Characters | Fill the next accepting position |
| Backspace / Delete | Clear the previous / next position |
| Arrow keys, Home, End | Native caret movement |
| Escape | Clears a `clearable` field |

The field is a native textbox; put the expected format in `description`.
Masks of digits and literals render `dir="ltr"` so they read the
same in right-to-left pages. Try it in the
[keyboard demo](https://salmonui.dev/demos/inputs/inputs-keyboard).

## SSR

The server renders the masked text of `value` / `defaultValue` (or the
`placeholder`) and the hidden named input, so the markup hydrates without a
mismatch and the form submits before hydration.

The label follows the shared [Field](https://salmonui.dev/docs/inputs/field#design-notes)
rule: a static `<label>` above the input.

## API

| Prop | Type | Default |
| --- | --- | --- |
| `mask` | `string` | required |
| `tokens` | `Record<string, string \| RegExp>` | |
| `placeholderChar` | `string` | `'_'` |
| `value`, `defaultValue` | raw `string` | `''` |
| `onValueChange` | `(raw, { masked, complete, source, reason }) => void` | |
| `submitValue` | `'raw' \| 'masked'` | `'raw'` |
| `localeText` | `{ incomplete, clear, validation* }` | English |
| shared field props | `label`, `description`, `errorMessage`, `invalid`, `validation`, `validateOn`, `size`, `clearable`, adornments | |

`ref` is the visible native `<input>`. Full signatures:
[`@salmonui/inputs/masked-field` API reference](https://salmonui.dev/docs/reference/inputs/masked-field).
