Guide

Formatting fields

Understand canonical and display fields, formatter lifecycle, server-prefilled values, and cleanup.

Formatting pairs a visible value with a canonical value suitable for submission. It requires the optional @samline/formatter peer in ESM, CJS, and browser-module consumers; the global IIFE bundles the formatter.

Install the optional peer

npm install @samline/forms @samline/formatter

Basic setup

Author the HTML with the canonical name:

<form id="checkout">
  <label for="phone">Phone</label>
  <input id="phone" name="phone" autocomplete="tel" />
  <button type="submit">Pay</button>
</form>
import { form } from '@samline/forms'

const checkout = form('checkout', {
  formats: {
    phone: {
      type: 'phone',
      field: 'phone',
      options: { country: 'MX' },
    },
  },
})

The mirror convention

format() synchronously transforms the field pair before loading the peer asynchronously:

RoleNameElementExample value
Visible displayphone_displayedOriginal input, renamed55 1234 5678
Canonical rawphoneHidden input appended to the form5512345678

Both names are first-class controller fields:

OperationCanonical nameDisplay name
getValue()Reads raw hidden value.Reads formatted visible value.
setValue()Writes raw value; formatter synchronizes display.Writes display value; formatter synchronizes raw.
watch() / observe()Receives raw changes.Receives display changes.
getData() / submitIncludes canonical raw key.Includes display key.
Validation errorsKey rules by canonical name.Visual attributes land on the visible input.

The hidden mirror is appended to the form, not inserted beside the visible input. This keeps wrapper selectors such as .field:has([css-error]) focused on the visible control.

Timing and readiness

format() and formatAll() are chainable and return immediately; they do not return a readiness promise.

  1. Synchronous phase: find the first supported visible field, rename it, create or reuse its hidden mirror, and register both names.
  2. Asynchronous phase: load @samline/formatter, attach the capture-phase input listener, and format an initial value.
  3. Missing peer: log one cached console.error for the module instance and roll back fields created by that call.

Avoid submitting in the same synchronous turn in which formatting is first configured. Construction-time formats and normal user interaction give the peer time to resolve.

Supported fields

  • Visible HTMLInputElement controls except type="hidden".
  • HTMLTextAreaElement controls.
  • Selects are not formatter targets.
  • When several visible controls share the same canonical name, the first matching control is formatted.
  • displayField is valid only when field is one string. Arrays derive one ${field}_displayed name per canonical field.

Server-prefilled values

An existing visible value is formatted once after the peer loads. The initial pass defaults interpretInputAs to auto, which lets a canonical date such as 19901212 become its configured display form. Later events from the visible field and re-bind operations default to display, so a full-length paste such as 12121990 remains in display order. Writes to the canonical hidden mirror use auto. An explicit interpretInputAs in options always wins:

checkout.format({
  type: 'date',
  field: 'birthday',
  options: {
    datePattern: ['d', 'm', 'Y'],
    dateRawPattern: ['Y', 'm', 'd'],
    interpretInputAs: 'raw',
  },
})

Existing mirrors and cleanup

  • A pre-authored <input type="hidden" name="phone"> or element marked data-formatter-raw-for="phone" is reused.
  • reset() restores native defaults for both visible and raw fields.
  • destroy() restores the visible canonical name and removes only mirrors created by this controller.
  • Pre-authored mirrors survive destroy().
  • Repeated format() calls do not duplicate listeners or mirrors. They reformat the current value, but the installed input handler retains its original options. Destroy and recreate the controller when options must change reliably at runtime.

Distribution behavior

SurfaceFormatter availability
@samline/forms ESM/CJSInstall @samline/formatter in the consuming project.
@samline/forms/browserSame optional-peer requirement; importing also installs globalThis.Forms.
Global IIFEFormatter is bundled; no separate peer installation is needed.

Phones with formatter 3

@samline/formatter 3.0.0 makes phones opt-in so that forms without a phone field do not ship libphonenumber-js (about 140 KB). You do not need to do anything: the first time a field is formatted with type: 'phone', forms loads @samline/formatter/phone and calls registerPhone() for you. Bundlers put that subpath in its own lazy chunk. If your app already called registerPhone(), forms reuses it. With formatter 2.x phones are always included. The global IIFE bundles phone support.

Text casing and slugs

With @samline/formatter 3.1.0 or newer, type: 'text' applies a casing mode and type: 'slug' builds a URL slug while the user types. The visible input keeps a trailing separator so the space key works, and the hidden input carries the final slug.

const post = form('post', {
  formats: {
    title: { type: 'text', field: 'title', options: { case: 'title', smallWords: ['de', 'la'] } },
    slug: { type: 'slug', field: 'slug', options: { replacements: { '&': 'y' }, maxLength: 60 } },
  },
})

Formatter 3.3.0 adds two slug options: charMap transliterates other scripts ('cyrillic', 'greek', 'german', your own map or several of them), which are dropped without it, and preserve keeps characters such as . and _, for example options: { charMap: 'cyrillic', preserve: '.' }.

The global IIFE bundles formatter 3.3.0, so both types and these options work from the CDN script too.

The IIFE does not expose the formatter’s regex object or its check-digit validators on window.Forms. Import them from the peer in module builds, or load the formatter global next to the forms script; see Browser globals.

Validating formatted fields

Rules keyed by the canonical name read the hidden raw value. A phone, creditCard or general raw value has no delimiters, a numeral raw value has no prefix or group separators, and a date or time raw value keeps the visible text. Pick the rule for that value, or read values.<name>_displayed in validate to test what the user sees; the regex page has examples with regex.date() and regex.numeral().