Reference

API reference

Every FormController method, browser registry helper and pure utility exported by @samline/forms, grouped by task.

Every public method is listed here, grouped by lifecycle. Most methods are chainable and return the same FormController. Focused pages cover native control behavior, accessible validation, and formatting lifecycle without hiding those contracts outside the site.

Lifecycle

Registry helpers (vanilla)

  • browser — module-level singleton that wraps form() with newForm / destroyForm / available. Mirrors the IIFE surface without auto-installing a global.
  • browser.newForm — build + register a controller under browser.available[id].
  • browser.destroyForm — destroy + unregister a controller by id.
  • browser.available — registry of active controllers keyed by id.

Submission

Field observation

Field values

Validation

State and data

  • getData() — return plain object + FormData for the form.
  • getState() — return a snapshot of values, errors, and metadata.
  • append(options) — inject a DOM node into the form.

Pure helpers

These do not require a controller. They accept plain values or a raw HTMLFormElement and return results — safe to tree-shake into any bundle.


Per-method reference

Lifecycle

form(target, options?)

Creates a new controller bound to a form. This is the main entry point of @samline/forms.

function form(target: FormTarget, options?: FormControllerOptions): FormController
  • target — string id, HTMLFormElement, ref-like { current } object, or null/undefined.
  • options — controller configuration. See Configuration.

On creation the controller wires delegated input and submit listeners, including support for controls associated through form="id", starts a MutationObserver on the form subtree, optionally enables autoSubmit, and synchronizes initial css-filled state. Initial visual synchronization is independent of autoValidate; only the initial validation pass is conditional on that option.

An unresolved id, non-form element, null, or empty ref still returns an inert controller. Its element is null, reads return empty/missing values, and chainable writes are no-ops. String ids and ref-like values are resolved only once; create a new controller after the element mounts. Avoid binding multiple controllers to one form because each installs its own listeners.

createFormController(target, options?)

The underlying factory used by form(). It accepts the same arguments and returns the same FormController; use it when the explicit factory name reads better in framework integrations.

element

Read-only getter for the bound HTMLFormElement, or null if the binding target was unresolved at construction time. f is an alias kept short for fluent setup.

readonly element: HTMLFormElement | null
readonly f: HTMLFormElement | null

options

Read-only normalized FormControllerOptions. The controller creates a merged options object, and attributes always contains both resolved attribute names.

readonly options: FormControllerOptions

reset()

Restores native and formatted default values, clears manual and validation errors plus aria-invalid, calls field watchers with the restored values, then notifies subscribers. It dispatches no input events, runs no validation, does not disable auto-submit, and does not reset submitCount. A native reset button runs the same state pass after the browser restores defaults. When the controller is already validated, filled attributes are recalculated immediately from default values.

addCleanup(cleanup)

Registers controller-owned teardown work and returns an idempotent unregister function. Unregistering removes the callback without invoking it. Remaining callbacks run once in reverse registration order during destroy(); exceptions are reported and do not stop later cleanup. Registering after destruction invokes the cleanup immediately.

addCleanup(cleanup: FormCleanup): () => void

const unregister = controller.addCleanup(() => adapter.destroy())
unregister() // optional: remove without running

destroy()

Removes all controller listeners, disconnects the observer, cancels pending auto-submit, runs registered cleanups in reverse order, drops callbacks, clears stored errors and submit tracking, and cleans up formatter ownership. Formatted visible names are restored and only controller-created raw mirrors are removed. Existing visual attributes are not stripped. Public methods remain callable: reads still inspect the DOM, while writes, error changes, validation and new registrations become no-ops, so late async callbacks cannot repaint the form. Calling destroy() more than once is safe.

Submission

onSubmit(callback, preventDefault?)

Registers a handler that runs when the form is submitted and validation passes. Multiple handlers can be registered; each runs in registration order.

onSubmit(
  callback: FormSubmitHandler,
  preventDefault?: boolean  // default: true
): FormController

The submit pipeline clears manual errors when configured, validates, synchronizes aria-invalid, increments submitCount, and invokes every handler in registration order when valid. Invalid submissions are always intercepted and focus moves to the first focusable invalid field in document order, except when auto-submit started the submit. If any valid-submit handler uses the default preventDefault: true, the event is prevented for all handlers. Handlers may return Promise<void>; getState().isSubmitting remains true while async handlers from any concurrent submission are pending. Fulfilled and rejected promises both settle the submitting state; a rejection is reported with console.error. Promise settlement does not delay native navigation when every handler opts out of prevention. There is no per-handler unsubscribe method; destroy() clears all handlers. A successful named submit button contributes its name/value to fresh data and formData values.

autoSubmit(options?)

Enables native auto-submit. Every handled input schedules form.requestSubmit() (or the package’s submit fallback). Pass { debounce: ms } to delay. Auto-submit itself does not validate; validation occurs when the resulting submit event enters the normal pipeline. Disabling or destroying cancels pending timers, and re-enabling uses only the newly supplied debounce.

autoSubmit(options?: boolean | AutoSubmitOptions): FormController

disableAutoSubmit()

Turns auto-submit off and cancels any pending debounce timer. Equivalent to autoSubmit(false).

Field observation

watch(field, callback)

Chainable field observer. When a form is bound, the callback fires immediately and after matching handled input events; an inert controller stores the callback without an initial call. DOM mutations alone do not invoke field watchers, except an option-list change that changes a select’s value. watch() returns the controller instead of an unsubscribe function.

Pass an array of names to watch several fields with one callback, which receives (values, changed, form, state) (FormFieldsWatcher). values has one entry per listed field; changed names the field that triggered the call, or is null on registration and after reset(). It fires once per change of any listed field.

observe(field, callback)

Like watch (including the array form), but returns an idempotent unsubscribe function. The callback receives (value, field, form, state) after error clearing, validation, and visual synchronization for the input event, but before whole-form subscribers are notified.

unwatch(field?, callback?)

Removes watched callbacks: no args (clear all), field only (clear all for that field), or field + callback (clear one specific watcher). An array of names removes watchers registered with that same list, optionally only one callback; a single name never removes list watchers.

subscribe(listener)

Registers a listener that always fires immediately and returns an unsubscribe function. Notifications occur for handled input, setValue, manual-error changes, reset, auto-submit toggles, submit attempts, and observed DOM mutations, including option-list changes that change a select’s value. Direct validate() / revalidate() calls update validation state but do not independently notify subscribers.

Field values

setValue(name, value)

Writes a value and dispatches one bubbling input event from the first matching field, so the controller pipeline runs once. Returns the controller unchanged when the field does not exist.

Control-specific checkbox, radio, file, multi-select, repeated-name, and [] behavior is specified in the form-control matrix.

setOptions(name, options, config?)

Replaces the <option> / <optgroup> children of every <select> named name. Entries are strings, numbers, { value, label?, disabled?, selected? } or { label, options } groups; labels are written as text. The current selection is kept when its value is still listed (keepValue: true by default) unless an option has selected: true. One bubbling input event runs the pipeline only when the selected value changes. See setOptions().

getValue(name)

Returns the normalized value of a field: string, string[], File[], or undefined.

The exact scalar/array behavior differs for radio groups, checkbox groups, multiple selects, files, repeated bare names, and [] names. See the reading values matrix.

getField(name)

Returns the underlying DOM field(s) for a given name: a single FormFieldElement, an array (for repeated names like radio/checkbox groups), or null.

prefill(fieldName?)

Populates the form (or one field) from window.location.search. Values are strings and each query entry delegates to setValue, so normal event effects apply. A repeated key (?tags[]=a&tags[]=b) is written once as an array, and auto-submit runs once after the whole batch. In non-DOM environments it is a no-op.

format(config)

Apply an @samline/formatter pipeline to one or more input/textarea fields. The method synchronously creates the canonical/display pair, returns the controller immediately, then asynchronously loads and binds the peer. A custom displayField works only for one field; arrays derive <field>_displayed separately. Selects and hidden visible targets are unsupported. Read the complete formatting lifecycle and mirror contract.

Initial server-rendered values are normalized after the peer loads with automatic raw/display interpretation unless interpretInputAs is explicitly configured. See server-prefilled values.

formatAll(config)

Alias of format() for readability when field is string[].

Validation

validate(fields?)

Runs configured rules and returns merged validation plus manual errors. With a field list, existing validation errors for other fields remain. Names without rules have their prior validation errors removed. The method marks the form as validated and synchronizes visual attributes, but does not independently notify subscribers. See validation semantics.

revalidate(fields?)

Alias of validate kept separate for readability at call sites that want to express “re-run validation now”.

setErrors(fields)

Pushes manual errors into the form. Two overloads: array form (string[], default message “Invalid value.”) and map form (FormErrors, custom messages per field).

clearErrors(fields?)

Removes manual errors. Validation errors from rules are not touched. Visual attributes are re-synced for the affected fields.

State and data

getData()

Returns fresh { data, formData } values. Native successful-control rules apply, repeated names become arrays in data, and empty file placeholders are removed. Files remain File objects. See serialization differences.

getState()

Returns a fresh snapshot: { values, errors, filledFields, isValid, isValidated, autoSubmit, isSubmitting, submitCount }. It is a pure read and does not validate or notify. isValid only means the currently stored merged error map is empty, so an unvalidated form may appear valid. isSubmitting tracks pending async submit-handler groups, including overlapping valid submissions.

append(options)

Creates a node and assigns content to innerHTML; sanitize untrusted content. When class is present, the first existing descendant matching its first class token is removed. The method clears the field cache but does not validate, notify subscribers, or schedule auto-submit. Appended nodes survive reset() and destroy(). Returns the node or null for an inert controller.

const banner = controller.append({ tag: 'p', content: '', class: 'status' })
if (banner) banner.textContent = untrustedMessage // safe text-only alternative

Pure helpers

parseFormData(formElement, submitter?)

function parseFormData(
  formElement: HTMLFormElement,
  submitter?: HTMLElement | null
): SerializedFormResult

Same serializer the controller uses internally. Pass the successful submit button to include its name/value. Repeated names become arrays, empty file placeholders are filtered, and reserved names such as constructor and __proto__ remain ordinary own properties. This helper has no validation or controller side effects.

validateValues(values, schema)

function validateValues(values: FormValues, schema: ValidationSchema): ValidationResult

Runs every exact schema key against a values map. Returns { isValid, errors } without DOM or controller side effects. Wildcard schema keys are not expanded.

validateFieldValue(field, value, rules, values)

function validateFieldValue(
  field: string,
  value: FormFieldValue,
  rules: FieldValidationRules,
  values: FormValues
): string[]

Runs every built-in and custom rule against one value and returns all messages. Pattern and numeric/range checks skip empty values; bounds are inclusive; sameAs compares two non-empty values; custom validators still run. each validates array members and flattens their messages into the returned string[], but this DOM-free helper cannot provide context.element. This pure helper does not react to dependsOn. See the rule behavior table.

Registry helpers (vanilla)

The vanilla entrypoint exports a browser singleton with the same shape as the IIFE bundle’s window.Forms — but as a plain ESM value with no globalThis side-effect. Use it from a bundler when you want the registry ergonomics without the IIFE.

browser

const browser: FormsApi

Module-level singleton. Exposes form, newForm, destroyForm, and available. Spread it into your own globals ({ ...browser, regex }) or call its methods directly. The registry is shared across spreads, so window.Form.available and browser.available always point to the same object. See the Browser registry helpers section in the getting-started guide and FormsApi for the exact shape.

browser.newForm

Build a controller via browser.form(id, options) and store it in browser.available[id]. An existing controller under the id is destroyed before replacement. A missing id logs Form ID is required and returns undefined.

const contact = browser.newForm({
  id: 'contact-form',
  options: {
    validators: { email: { required: true } },
  },
})

browser.destroyForm

Look up browser.available[id], call destroy(), and delete the entry. A missing id logs an error; an absent entry logs a warning.

browser.destroyForm('contact-form')

browser.available

Shared mutable registry: { [id: string]: FormController }. Prefer newForm() and destroyForm() to manage it.

for (const controller of Object.values(browser.available)) {
  controller.validate()
}

For an equivalent surface in a no-bundler setup, see the Browser global reference.

External integration

regex from @samline/formatter

A catalog of validation patterns, each paired with an error message, for the pattern rule. Since formatter 3.2.0 it covers Mexican, US and European identifiers and has builders that follow a format() mask (regex.date(options)), and the peer exports check-digit validators (isValidCurp, isValidIban, isValidCard…) for the validate rule. The dedicated regex page shows how each one fits forms, including which value a formatted field validates.