Reference

API reference

Reference for format(), FORMAT_TYPES, isFormatType and the advanced helpers of @samline/formatter, with parameters, returns and errors.

Every public symbol is listed here in the order it appears in the source. Each entry shows the signature, parameter table, return shape, and a runnable example.

Side effects per function

Use this as a quick lookup when you need to know what a function will touch.

FunctionDOM mutationNetworkReads globalsReads timeNotes
format(value, type, options?)nonononoPure string transformer. Safe to call on every keystroke.
isFormatType(value)nonononoType-guard. No allocation beyond the comparison.
FORMAT_TYPESn/an/an/an/aA readonly tuple; iteration is the only legitimate use.
regex.<key>.patternnonononoA compiled RegExp. regex.<key> is also callable for parametric variants.
regex.<key>.errorMessagen/an/an/an/aA short human-readable message paired with the pattern.
isValidCard() and the other check-digit validatorsnonononoReturn a boolean; never throw, non-strings return false.
registerPhone()nonononoFrom /phone. Sets the one module-level switch that enables 'phone'.
isPhoneRegistered()nonoyesnoReads the phone switch.
formatPhonenonononoFrom /phone. Lower-level helper called by format(..., 'phone').
getRawValuenonononoLower-level raw value extractor.
getDateValueFromRawnonononoLegacy round-trip helper for dates.
getTimeValueFromRawnonononoLegacy round-trip helper for times.
looksLikeRawDateValuenonononoHeuristic test for the v2.0.0 auto mode.
looksLikeRawTimeValuenonononoHeuristic test for the v2.0.0 auto mode.
stripPrefixAndSuffixnonononoStrips the configured prefix and suffix from a string.

The format function and every helper it delegates to are referentially transparent — the same (value, formatType, options) triple always returns the same FormatterResult. This is what enables SSR re-rendering and testing without mocks. The only module state is the phone switch: once registerPhone() runs, 'phone' formats instead of throwing. The Intl display helpers and the date tools are listed on their own pages; formatRelativeTime, formatCalendar, isToday and the parsers that fill a missing date read the clock when now is omitted.

format(value, formatType, options?)

The main entry point. Pure, deterministic, framework-agnostic.

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

Parameters

NameTypeRequiredDescription
valueunknownyesThe raw value typed by the user. null, undefined, and '' return an empty result.
formatTypeFormatTypeyesOne of the seven supported format types. Throws TypeError if invalid, or for 'phone' before registerPhone().
optionsFormatOptionsnoPer-type options. See Configuration.

Returns

A FormatterResult with the formatted display string, the raw backend string, and the echoed type.

Examples

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

registerPhone() // phones are opt-in since 3.0.0

format('5512345678', 'phone')
// => { formatted: '55 1234 5678', raw: '5512345678', type: 'phone' }

format('4111111111111111', 'creditCard')
// => { formatted: '4111 1111 1111 1111', raw: '4111111111111111', type: 'creditCard' }

format('4111111111111111', 'creditCardType')
// => { formatted: 'visa', raw: '4111111111111111', type: 'creditCardType' }

FormatterResult

The shape returned by format. All fields are readonly.

interface FormatterResult {
  readonly formatted: string // display value
  readonly raw: string // canonical backend value
  readonly type: FormatType // echo of the requested format type
}
  • formatted is the display string (with delimiters, prefix, etc.). Bind this to the visible <input>.
  • raw is the canonical value to ship to the server. Its exact shape depends on the format and options: phone/card values are digits (with a possible leading + for phones), while general values can retain letters or configured affixes. Mirror it into a hidden input.
  • type is the requested format type — useful for debugging or when the same result object is piped through downstream layers.

FormatType

Union of the nine supported format types.

type FormatType =
  | 'general'
  | 'phone'
  | 'numeral'
  | 'date'
  | 'time'
  | 'creditCard'
  | 'creditCardType'
  | 'text'
  | 'slug'

FormatOptions

The options bag passed to format. See Configuration for the full per-formatType field reference.

type FormatOptions = Partial<
  FormatGeneralOptions &
    FormatNumeralOptions &
    FormatDateOptions &
    FormatTimeOptions &
    FormatCreditCardOptions
> & {
  country?: string
  dateRawPattern?: DatePatternType
  dateRawPatternDelimiter?: string
  timeRawPattern?: TimePatternType
  timeRawPatternDelimiter?: string
  /** @deprecated Prefer the dedicated `suffix` option. */
  tailPrefix?: boolean
  prefixMode?: 'lock' | 'passthrough'
  rawPrefix?: boolean
  suffix?: string
  suffixMode?: 'lock' | 'passthrough'
  rawSuffix?: boolean
  rawDecimalPadding?: boolean
  interpretInputAs?: 'auto' | 'display' | 'raw'
}

FormatNumeralOptions includes numeralDecimalPadding?: boolean since 3.0.0, and numeralThousandsGroupStyle is the exported NumeralThousandsGroupStyle literal union.

FORMAT_TYPES

A readonly tuple of every supported type. Useful for iterating, building pickers, or driving type-driven UIs.

import { FORMAT_TYPES } from '@samline/formatter'

FORMAT_TYPES
// => ['general', 'phone', 'numeral', 'date', 'time', 'creditCard', 'creditCardType', 'text', 'slug']

isFormatType(value)

Type-guard that narrows an unknown string to FormatType.

import { isFormatType } from '@samline/formatter'

function safeFormat(value: string, formatType: string) {
  if (!isFormatType(formatType)) {
    throw new Error(`Unsupported format type: ${formatType}`)
  }
  return format(value, formatType)
}

regex

A pre-built object of validation patterns, each pairing a RegExp with a ready-to-use errorMessage. See Regex for the full table.

import { regex } from '@samline/formatter'

regex.email.pattern.test('foo@bar.com') // true
regex.email.errorMessage // 'Please enter a valid email address.'

Static entries expose .pattern and .errorMessage. The builders digits, phone, creditCard, url, uuid, date, time, numeral, postalCode, password and custom return a fresh { pattern, errorMessage }; date, time and numeral take the same options as format():

regex.postalCode({ country: 'CA' }).pattern.test('K1A 0B1') // true
regex.date({ datePattern: ['d', 'm', 'Y'] }).pattern.test('31/04/2026') // false

Check-digit validators

isLuhn, isValidCard, isValidClabe, isValidNss, isValidCurp, isValidRfc, isValidIban, isValidRoutingNumber and isValidDniEs verify the check digit that a pattern cannot. Each takes value: unknown, ignores spaces and hyphens, upper-cases letters and returns a boolean. They are also on window.Formatter.checks. See Check-digit validators for what each one verifies.

import { isValidCard, isValidIban } from '@samline/formatter'

isValidCard('4111 1111 1111 1111') // true
isValidIban('GB82 WEST 1234 5698 7654 32') // true
isValidIban('GB82 WEST 1234 5698 7654 33') // false — one digit changed

Phone support

import { formatPhone, isPhoneRegistered, registerPhone } from '@samline/formatter/phone'

isPhoneRegistered() // false
registerPhone()
isPhoneRegistered() // true
formatPhone('5512345678', 'MX', '-') // '55-1234-5678'

registerPhone() enables format(value, 'phone') for every entrypoint; call it once at startup. isPhoneRegistered() is also exported from the root. Without registration, format(value, 'phone') throws a TypeError, even for an empty value, so a missing setup fails on the first render instead of on the first digit.

Browser global: window.Formatter

The browser entrypoints register a focused Formatter object on window. It exposes format, intl, regex, checks (the check-digit validators) and version; lower-level root helpers are not added to the global. formatter.phone.global.js registers phones on load; formatter.global.js does not. The optional formatter.date.global.js add-on, loaded after either one, adds date with the date tools.

interface FormatterGlobal {
  format: (value: unknown, formatType: FormatType, options?: FormatOptions) => FormatterResult
  intl: typeof import('@samline/formatter/intl')
  regex: typeof regex
  checks: Pick<
    typeof import('@samline/formatter'),
    | 'isLuhn'
    | 'isValidCard'
    | 'isValidClabe'
    | 'isValidCurp'
    | 'isValidRfc'
    | 'isValidNss'
    | 'isValidIban'
    | 'isValidRoutingNumber'
    | 'isValidDniEs'
  >
  version: string
  date?: typeof import('@samline/formatter/date') // with formatter.date.global.js
}
<script src="https://cdn.jsdelivr.net/npm/@samline/formatter@3.3.1/dist/browser/formatter.phone.global.js"></script>
<script>
  const result = window.Formatter.format('5512345678', 'phone')
  console.log(result.formatted) // '55 1234 5678'
  console.log(window.Formatter.version) // '3.2.1'
</script>

Advanced helpers

The building blocks are also exported for advanced consumers. Treat them as an internal API — they are exported because they are useful, but the public contract is format.

import {
  getRawValue,
  getDateValueFromRaw,
  getTimeValueFromRaw,
  stripPrefixAndSuffix,
} from '@samline/formatter'

getRawValue('1,234.50', 'numeral') // '1234.50'
getDateValueFromRaw('2026-05-12', { datePattern: ['d', 'm', 'Y'] }) // '12052026'
getTimeValueFromRaw('14:30', { timePattern: ['h', 'm', 's'] }) // '143000'
stripPrefixAndSuffix('$100', { prefix: '$' }) // '100'

The /vanilla entrypoint exposes the exact same surface as the root import. The two are aliases by design — pick whichever reads better in your codebase.