Reference

Configuration options

Every option accepted by format(), with defaults, per-format behavior and the prefix and suffix rules for general masks.

format(value, formatType, options?) accepts an options object whose shape depends on formatType. All fields are optional; sensible defaults cover the common case (space-delimited MX phones, slash-delimited dates, etc.).

import type { FormatOptions, FormatType } from '@samline/formatter'

function format(value: unknown, formatType: FormatType, options?: FormatOptions): FormatterResult

Internally FormatOptions is the intersection of the built-in engine’s per-type option interfaces (numeral, date, time, card and general; the engine started as a port of cleave-zen 0.0.17 and is maintained in this package since 3.0.0) plus a few package-specific extras (country, dateRawPattern, timeRawPattern, prefixMode, rawPrefix, suffix, suffixMode, rawSuffix, tailPrefix). Only the fields relevant to your formatType are read; everything else is ignored.

Common fields

These apply to most format types.

Field Type Default Applies to Notes
country string (ISO 3166-1 alpha-2) 'MX' for phone, '' otherwise phone Passed to libphonenumber-js’s AsYouType. Phones need registerPhone() (see phone).
delimiter string phone: ' '; numeral: ',' ('.' with a ',' mark); date '/'; time ':'; card ' '; general '' all Separator for the formatted display. An empty string disables visible separation while preserving date/time auto-detection.
delimiters string[] [] general, numeral Additional separators (e.g. [' ', '-']).
prefix string '' general, numeral Prepended to the display. See Prefix & suffix on general for how the formatter manages it (including prefixMode and rawPrefix).
tailPrefix boolean false general, numeral Legacy: when true (and suffix is not provided), prefix is treated as a suffix (stripped from the end). Prefer the new dedicated suffix option for new code.

general

Type: 'general'

Block-based masking with custom delimiter / delimiters. Pair with blocks to define group sizes.

Field Type Default Notes
blocks number[] [] Required. Defines block sizes (e.g. [4, 4, 4, 4]). Since 2.1.0 a missing or empty array throws a descriptive TypeError for non-empty values.
delimiterLazyShow boolean false Show delimiters only when the next block has content.
numericOnly boolean false Strip non-digit characters. Applied to both display and (when rawPrefix: true / rawSuffix: true) to the canonical raw mirror — see Prefix & suffix on general.
uppercase boolean false Force uppercase.
lowercase boolean false Force lowercase.
case 'upper' | 'lower' | 'title' | 'sentence' | 'capitalize' – Since 3.1.0. One casing mode; takes precedence over uppercase / lowercase. smallWords and locale apply as in text.
prefixMode 'lock' | 'passthrough' 'lock' 'lock' (default) auto-prepends the configured prefix; 'passthrough' reflects whatever the user has typed of the prefix instead (so E sticks for a configured EASY). See Prefix & suffix on general.
rawPrefix boolean false When true, the raw mirror includes the configured prefix. The body is only digits-only when numericOnly is enabled.
suffix string '' Tail decoration appended at the end of the display (e.g. ' USD', '-END'). Independent from prefix; can differ from it.
suffixMode 'lock' | 'passthrough' 'lock' 'lock' (default) auto-appends the configured suffix; 'passthrough' reflects whatever the user has typed of the suffix instead.
rawSuffix boolean false When true, the raw mirror includes the configured suffix. Default false.

Prefix & suffix on general

general formats can decorate the visible value with a head (prefix) and/or a tail (suffix). The formatter manages both entirely on its own — it never delegates prefix handling to the general engine, whose own prefix step discards any input that doesn’t already start with the configured prefix, freezing the field at the literal prefix.

prefixMode — how the user interacts with the head decoration

  • 'lock' (default): the user types only the body; the formatter auto-prepends the configured prefix on every call. If the input happens to start with the prefix (paste case), the prefix is stripped before processing.
  • 'passthrough': the user types (or pastes) the prefix themselves. Every keystroke that matches the prefix sticks, so E, EA, EAS, EASY all stay in the field until you type past it.
// Auto-prepend `EASY`, user types only the 9 digits
format('123456789', 'general', { blocks: [13], prefix: 'EASY' })
// => { formatted: 'EASY123456789', raw: '123456789', type: 'general' }

// User types the prefix themselves character by character
format('EASY1', 'general', {
  blocks: [13],
  prefix: 'EASY',
  prefixMode: 'passthrough',
})
// => { formatted: 'EASY1', raw: '1', type: 'general' }

suffixMode — how the user interacts with the tail decoration

Mirror image of prefixMode. 'lock' (default) auto-appends the configured suffix; 'passthrough' lets the user type it character by character.

format('123456789', 'general', { blocks: [12], suffix: 'USD' })
// => { formatted: '123456789USD', raw: '123456789', type: 'general' }

format('12345US', 'general', {
  blocks: [12],
  suffix: 'USD',
  suffixMode: 'passthrough',
})
// => { formatted: '12345US', raw: '12345', type: 'general' }

rawPrefix / rawSuffix — what the raw mirror contains

The default raw value is the unformatted body the user typed. With numericOnly: true it is digits-only. Opt in with rawPrefix: true / rawSuffix: true when the backend needs the canonical value with the decoration included:

// Backend wants the canonical identifier
format('123456789', 'general', {
  blocks: [13],
  prefix: 'EASY',
  rawPrefix: true,
})
// => { formatted: 'EASY123456789', raw: 'EASY123456789', type: 'general' }

// Both ends canonical
format('12345', 'general', {
  blocks: [11],
  prefix: 'PRE-',
  suffix: '-END',
  rawPrefix: true,
  rawSuffix: true,
})
// => { formatted: 'PRE-12345-END', raw: 'PRE-12345-END', type: 'general' }

When rawPrefix / rawSuffix is set, the body part of raw is derived from the formatted body (with the display delimiter stripped) rather than from the user’s typed input verbatim. This means numericOnly and the case transforms (uppercase / lowercase) are honoured in the canonical raw too — a user fat-fingering letters into a numericOnly: true field no longer ships a contaminated identifier to the backend.

// Fat-fingered input — display is clean AND the canonical raw is clean.
format('1a2b3c4d5e6f7g8h9i', 'general', {
  blocks: [4, 5],
  delimiter: ' ',
  prefix: 'EASY',
  prefixMode: 'lock',
  rawPrefix: true,
  numericOnly: true,
})
// => { formatted: 'EASY1234 56789', raw: 'EASY123456789', type: 'general' }

With the default (rawPrefix: false / rawSuffix: false), raw mirrors the typed body without the formatter’s own delimiter / delimiters. Characters that numericOnly hides from the display are kept. Because the delimiters are removed, formatting a displayed value again returns the same raw (since 2.1.0):

const options = { prefix: 'ORD-', blocks: [4, 4], delimiter: '-', numericOnly: true }
format('12345678', 'general', options).raw // '12345678'
format('ORD-1234-5678', 'general', options).raw // '12345678'

In the default 'lock' modes, deleting a single character of the prefix or suffix (for example with Backspace) restores the whole decoration instead of duplicating it.

prefix + suffix combined

The two decorations are independent — different head and tail, different modes, different raw flags:

format('12345', 'general', {
  blocks: [11],
  prefix: 'PRE-',
  suffix: '-END',
})
// => { formatted: 'PRE-12345-END', raw: '12345', type: 'general' }

Backwards compatibility: tailPrefix

The historical prefix + tailPrefix: true shape (where prefix was repurposed as a tail decoration) is preserved for existing callers. When both suffix and prefix + tailPrefix: true are provided, the new suffix wins:

// Legacy shape still works
format('123456789', 'general', { blocks: [12], prefix: 'USD', tailPrefix: true })
// => { formatted: '123456789USD', raw: '123456789', type: 'general' }

// `suffix` wins when both are set
format('12345', 'general', {
  blocks: [8],
  prefix: 'X',
  tailPrefix: true,
  suffix: 'OK',
})
// => { formatted: 'X12345OK', raw: '12345', type: 'general' }

numeral

Type: 'numeral'

Thousand separators with optional decimal scaling.

Field Type Default Notes
numeralDecimalMark string '.' Decimal separator.
numeralThousandsGroupStyle 'thousand' | 'lakh' | 'wan' | 'none' 'thousand' Grouping style.
numeralIntegerScale number 0 Max integer digits.
numeralDecimalScale number 2 Max decimal digits.
numeralDecimalPadding boolean false Pad decimals with zeros up to numeralDecimalScale in formatted. Since 3.0.0; see Decimal padding.
rawDecimalPadding boolean false Pad decimals with zeros up to numeralDecimalScale in raw ('1234.50'). Since 3.0.0; see Decimal padding.
stripLeadingZeroes boolean true Strip leading 0s ('0042' → '42').
numeralPositiveOnly boolean false Disallow negative numbers.
signBeforePrefix boolean false Place the - sign before the prefix.

raw always uses a dot as the decimal mark. The default group delimiter is ',', or '.' when numeralDecimalMark is ',' (since 3.0.0; before, both used ',' and 1234,5 displayed as 1,234,5).

Decimal padding

numeralDecimalPadding: true pads the decimal part of formatted with zeros up to numeralDecimalScale. An integer gains the full set of zeros and a bare decimal part gains a leading 0. raw stays unpadded and dot-decimal — trailing decimal zeros are dropped — so it is the same before and after padding, and formatting the padded value again returns the same result.

format('1234567.5', 'numeral', { prefix: '$', numeralDecimalPadding: true })
// => { formatted: '$1,234,567.50', raw: '1234567.5', type: 'numeral' }

format('1234,5', 'numeral', {
  numeralDecimalMark: ',',
  delimiter: '.',
  prefix: ' €',
  tailPrefix: true,
  numeralDecimalPadding: true,
})
// => { formatted: '1.234,50 €', raw: '1234.5', type: 'numeral' }

To send the padded value to the backend, add rawDecimalPadding: true. It pads raw to exactly numeralDecimalScale digits, independently of numeralDecimalPadding, so it also works on every input event while the display stays unpadded:

format('1234.5', 'numeral', { rawDecimalPadding: true })
// => { formatted: '1,234.5', raw: '1234.50', type: 'numeral' }

format('1234', 'numeral', { numeralDecimalPadding: true, rawDecimalPadding: true })
// => { formatted: '1,234.00', raw: '1234.00', type: 'numeral' }
Options formatted for 1234.5 raw
none '1,234.5' '1234.5'
numeralDecimalPadding '1,234.50' '1234.5'
rawDecimalPadding '1,234.5' '1234.50'
numeralDecimalPadding + rawDecimalPadding '1,234.50' '1234.50'

Values without digits ('', '-') and numeralDecimalScale: 0 are never padded. Either way raw is stable when the displayed value is formatted again.

Padding while typing fights the caret (typing after 4.00 would hit the decimal limit), so apply it when the field loses focus or when you show a stored value, and format without it on input:

const options = { prefix: '$', numeralDecimalScale: 2 }
amount.addEventListener('input', () => {
  amount.value = format(amount.value, 'numeral', options).formatted
})
amount.addEventListener('blur', () => {
  const { formatted, raw } = format(amount.value, 'numeral', {
    ...options,
    numeralDecimalPadding: true,
  })
  amount.value = formatted
  hidden.value = raw
})

date

Type: 'date'

Formats display-order or canonical raw dates. The default interpretInputAs: 'auto' treats a complete delimiter-less value matching the raw pattern length as raw; partial or delimiter-bearing values are treated as display.

Field Type Default Notes
datePattern DatePatternType (['d', 'm', 'Y'] | …) ['d', 'm', 'Y'] Display pattern.
dateRawPattern DatePatternType ['Y', 'm', 'd'] Pattern used to derive the raw value from the formatted display.
dateRawPatternDelimiter string '-' Delimiter used in the raw value.
interpretInputAs 'auto' | 'display' | 'raw' 'auto' Select automatic shape detection or force an unambiguous input convention.
dateMin / dateMax string '' Optional bounds ('YYYY-MM-DD').
delimiter string '/' Display delimiter (use this to switch to - or .).

time

Type: 'time'

Formats display-order or canonical raw times using the same input interpretation modes as dates.

Field Type Default Notes
timePattern TimePatternType (['h', 'm', 's'] | …) ['h', 'm', 's'] Display pattern.
timeRawPattern TimePatternType ['h', 'm'] Pattern used to derive the raw value from the formatted display.
timeRawPatternDelimiter string ':' Delimiter used in the raw value.
interpretInputAs 'auto' | 'display' | 'raw' 'auto' Select automatic shape detection or force display/raw interpretation.
timeFormat '12' | '24' '24' 12-hour or 24-hour clock. On a 12-hour clock a typed 00 hour becomes 12 (since 3.0.0).
delimiter string ':' Display delimiter.

creditCard

Type: 'creditCard'

Brand-aware grouping. The package detects Visa, Mastercard, American Express, Discover, JCB (15 and 16 digits), Diners Club, UnionPay, Maestro, Mir, Dankort, InstaPayment and UATP; anything else groups as general in blocks of four.

Field Type Default Notes
strictMode boolean false Allow up to 19 digits (adds a last block).
delimiter string ' ' Group separator (set to '-' for dashes).

creditCardType

Type: 'creditCardType'

Returns the card brand as formatted ('visa', 'mastercard', 'amex', 'diners', 'discover', 'jcb', 'jcb15', 'maestro', 'mir', 'unionpay', 'dankort', 'instapayment', 'uatp' or 'general'). The raw is always digits-only.

This type does not consume any extra options — pass the card number and read result.formatted to get the brand.

text

Type: 'text' (since 3.1.0)

Free text with a casing mode and no mask. raw equals formatted. Title, sentence and capitalize come from @samline/string, bundled into formatter.

Field Type Default Notes
case 'upper' | 'lower' | 'title' | 'sentence' | 'capitalize' – Casing mode. Without it, uppercase / lowercase still apply.
smallWords string[] [] With case: 'title', words kept lower case unless first (['de', 'la']).
locale string | string[] – Locale for casing, for example 'tr'.
format('el señor de los anillos', 'text', { case: 'title', smallWords: ['de', 'los'] })
// => { formatted: 'El Señor de los Anillos', raw: 'El Señor de los Anillos', type: 'text' }

slug

Type: 'slug' (since 3.1.0)

A URL slug while the user types. formatted keeps a trailing separator so a space can become one; raw is the final, trimmed slug. Built on slugify from @samline/string.

Field Type Default Notes
delimiter string '-' Word separator.
replacements Record<string, string> {} Literal replacements applied first, for example { '&': 'y' }.
maxLength number – Maximum length; cuts at a separator when possible.
locale string | string[] – Locale for lower-casing.
charMap 'cyrillic' | 'greek' | 'german' | Record<string, string> | Array<…> – Since 3.3.0. Transliterates other scripts first; several are merged in order. Without it, letters outside Latin are dropped.
preserve string '' Since 3.3.0. Characters kept as they are, for example '._'.
format('Mi Página ', 'slug')
// => { formatted: 'mi-pagina-', raw: 'mi-pagina', type: 'slug' }

format('Привет мир', 'slug', { charMap: 'cyrillic' }).raw // 'privet-mir'
format('Grüße', 'slug', { charMap: 'german' }).raw // 'gruesse'
format('Release v1.2_beta', 'slug', { preserve: '._' }).raw // 'release-v1.2_beta'

A custom map such as { Å: 'Aa' } also matches the lower-case letter, because the slug is lower-cased first. Each map object is read once and cached, so pass a new object to change it.

phone

Type: 'phone'

Country-aware phone formatting via libphonenumber-js. The leading + is preserved in raw so international numbers keep their prefix.

Since 3.0.0 phone support is opt-in, so the core does not bundle libphonenumber-js. Call registerPhone() once before formatting phones, or load formatter.phone.global.js in the browser. Without it, format(value, 'phone') throws a TypeError that explains the fix.

import { format } from '@samline/formatter'
import { registerPhone } from '@samline/formatter/phone'

registerPhone()
Field Type Default Notes
country string 'MX' ISO 3166-1 alpha-2 country code (e.g. 'US', 'GB', 'AR'); case-insensitive since 2.1.0.
delimiter string ' ' Group separator (set to '-' for dashes, '.' for dots).

Examples

// US phone with dash delimiter
format('2025551234', 'phone', { country: 'US', delimiter: '-' })
// => { formatted: '(202)-555-1234', raw: '2025551234', type: 'phone' }

// Numeral with comma decimal mark (European style)
format('1234,5', 'numeral', { numeralDecimalMark: ',', delimiter: '.' })
// => { formatted: '1.234,5', raw: '1234.5', type: 'numeral' }

// Date with explicit dash delimiter and Y-m-d display
format('20260512', 'date', {
  datePattern: ['Y', 'm', 'd'],
  delimiter: '-',
})
// => { formatted: '2026-05-12', raw: '2026-05-12', type: 'date' }

// Numeral with prefix and tailPrefix (suffix)
format('100', 'numeral', { prefix: '$', tailPrefix: true })
// => { formatted: '100$', raw: '100', type: 'numeral' }

// general with auto-prepended prefix and canonical raw
format('123456789', 'general', {
  blocks: [13],
  prefix: 'EASY',
  rawPrefix: true,
})
// => { formatted: 'EASY123456789', raw: 'EASY123456789', type: 'general' }

// general with head + tail decorations (independent)
format('12345', 'general', {
  blocks: [11],
  prefix: 'PRE-',
  suffix: '-END',
  rawPrefix: true,
  rawSuffix: true,
})
// => { formatted: 'PRE-12345-END', raw: 'PRE-12345-END', type: 'general' }

To show stored values in a locale (currency, dates, relative time) rather than mask typing, see the Intl display helpers.