Appearance
Formhaus form definition 1.8
This page specifies the JSON format that @formhaus/core reads, and how FormEngine interprets it. The JSON Schema describes the shape; this page describes the behaviour. For the TypeScript types, see the Definition Reference.
Conventions
The key words MUST, MUST NOT, SHOULD and MAY are used as described in RFC 2119. They appear only where FormEngine enforces the rule by throwing an error or by its runtime behaviour.
- Core means
FormEnginefrom@formhaus/core. - Renderer means a UI layer that draws a definition:
@formhaus/react,@formhaus/vue, the Figma plugin, or a custom renderer built on core. - Value means an entry in
engine.values, keyed by fieldkey. - Node means an entry of a
fieldsarray: a field, a section or a group. - Empty (blank) means
undefined,null,''or[].notEmptymatches any value that is not blank, sofalseand0count as values. Forrequired, an uncheckedcheckboxorswitch(false) is also empty.
Versioning
This document describes Formhaus form definition 1.9. @formhaus/core 1.10 and later implement it. Format 1.8, implemented by @formhaus/core 1.9, is 1.9 without hidden fields in groups. Format 1.7, implemented by @formhaus/core 1.7 and 1.8, is 1.8 without option descriptions and disabled options, read-only fields and reorderable groups. Format 1.6, implemented by @formhaus/core 1.1 to 1.6, is 1.7 without file lists. Format 1.5, implemented by @formhaus/core 0.21 to 1.0, is 1.6 without option order. Format 1.4, implemented by @formhaus/core 0.20, is 1.5 without answer recall, exclusive options and the field autocomplete. Format 1.3, implemented by @formhaus/core 0.19, is 1.4 without the contains and notContains operators. Format 1.2, implemented by @formhaus/core 0.15 to 0.18, is 1.3 without the scale and rating types, option image, field columns and section layout. Format 1.1, implemented by @formhaus/core 0.14, is 1.2 without the field props. Format 1.0, implemented by @formhaus/core 0.11 to 0.13, is 1.1 without sections and groups.
- Additive changes, such as a new optional property or a new built-in field type, are minor versions.
- Removing or renaming a property, or changing the meaning of an existing one, is a major version.
- The JSON Schema
$id,https://formhaus.dev/schema/form-definition.json, is the canonical identifier of the format. It is unversioned and always describes the latest version. A major version publishes the previous schema under a versioned URL and states it in this section.
A definition MAY declare its format with formatVersion, a string MAJOR or MAJOR.MINOR, such as "1.9". Without it, core reads the definition as 1.9, but shows {{key}} tokens as written, keeps one file in a file field, ignores the 1.8 properties and rejects hidden fields in groups. A minor version newer than 1.9 is also read as 1.9. Core reports unsupported-format-version for a major version newer than 1, and invalid-type for a value of another shape. In both cases it does not check the rest of the definition.
A definition with sections or groups SHOULD declare "formatVersion": "1.1" or newer. Core 0.13 and older read a section or a group as a field of a custom type: they skip the fields inside it, and their validateSubmission() passes a group value without checks. checkDefinition() warns about a section or a group without format 1.1. Upgrade the server that runs validateSubmission() before the clients.
A definition with props MAY declare "formatVersion": "1.2". Core 0.14 reports props as unknown-property and ignores it; its renderers still pass it to custom components.
A definition with a scale or rating field SHOULD declare "formatVersion": "1.3". Core 0.18 and older read these types as custom types: they skip the type check, and their validateSubmission() accepts any value for them. checkDefinition() warns about a scale or rating field without format 1.3. Upgrade the server that runs validateSubmission() before the clients. A definition with option image, field columns or section layout MAY declare 1.3. Core 0.18 reports them as unknown-property, and its renderers draw plain options and a plain section.
A definition with a contains or notContains condition SHOULD declare "formatVersion": "1.4". Core 0.19 and older reject it with unknown-operator: the constructor and validateSubmission() throw. checkDefinition() warns about these operators without format 1.4. Upgrade the server that runs validateSubmission() before the clients.
A definition whose texts recall answers MUST declare "formatVersion": "1.5" or newer. Without it, and in core 0.20 and older, the texts show {{key}} as written. checkDefinition() warns about a {{key}} token without format 1.5.
A definition with an exclusive option SHOULD declare "formatVersion": "1.5". Core 0.20 and older report exclusive as unknown-property and ignore it: their engine keeps the other answers, and their validateSubmission() accepts an exclusive option with other values. checkDefinition() warns about an exclusive option without format 1.5. Upgrade the server that runs validateSubmission() before the clients.
json
{ "formatVersion": "1.5", "id": "contact", "title": "Contact", "submit": { "label": "Send" } }A definition with a field autocomplete MAY declare "formatVersion": "1.5". Core 0.20 reports autocomplete as unknown-property, and its renderers do not set the attribute. checkDefinition() warns about autocomplete without format 1.5.
A definition with a field randomize or an option pinned MAY declare "formatVersion": "1.6". Core 1.0 and older report them as unknown-property and show the written order. checkDefinition() warns about randomize or pinned without format 1.6.
A file field with multiple MUST declare "formatVersion": "1.7" or newer. Without it, and in core 1.6 and older, core reports multiple as unknown-property and the field keeps one file, so a definition written before 1.7 behaves as before. checkDefinition() warns about multiple without format 1.7. The validateSubmission() of core 1.6 and older fails a list in a file field with the file message. Upgrade the server that runs validateSubmission() before the clients. The renderers of core 1.6 and older draw a file list as a picker for one file and submit one file, which a 1.7 server reads as a list of one. A minLength above 1 then fails on the server.
An option description or disabled, a field readOnly and a group reorderable MUST declare "formatVersion": "1.8" or newer. Without it, and in core 1.8 and older, core reports them as unknown-property, and the engine, validateSubmission() and the renderers ignore them, so a definition written before 1.8 behaves as before. checkDefinition() warns about them without format 1.8. The validateSubmission() of core 1.8 and older accepts a disabled option. Upgrade the server that runs validateSubmission() before the clients.
A group with a hidden field MUST declare "formatVersion": "1.9" or newer. Without it, and in core 1.9 and older, core reports the field as invalid-nesting: the constructor and validateSubmission() throw. Upgrade the server that runs validateSubmission() before the clients.
Document structure
A definition is a JSON object. The JSON Schema rejects unknown properties at every level. checkDefinition() reports them as unknown-property warnings, and the engine ignores them.
| Property | Type | Required | Meaning |
|---|---|---|---|
$schema | string | no | Editor hint. Core ignores it. |
formatVersion | string | no | Format version of the definition. |
id | string | yes | Form identifier. Renderers use it to detect a new form. |
lang | string | no | BCP 47 language tag of the texts, such as "ru". Renderers set it as the lang attribute of the form. See Translations. |
messages | object | no | Validation message templates by message key. |
labels | object | no | Renderer label templates by label key. |
i18n | object | no | Translation keys for title, description, messages and labels. |
title | string | yes | Form title for host UI and Figma output. Renderers do not display it. |
description | string | no | Plain text shown under the title by host UI and Figma output, up to 1000 characters. Renderers do not display it. |
submit | action | yes | The submit action on the last step. |
cancel | action | no | A cancel action. Renderers show it on every step. |
fields | node[] | no | Fields, sections and groups of a single-step form. |
steps | step[] | no | Steps of a multi-step form. |
A form is multi-step when steps is a non-empty array. Otherwise it is single-step and uses fields. A definition with neither is a valid empty form.
A definition MUST NOT have both a non-empty fields and a non-empty steps. The FormEngine constructor throws on it.
Fields
| Property | Type | Meaning |
|---|---|---|
key | string, required | Key of the value. Keys are flat: "address.city" stays one key. |
type | string, required | Field type. |
label | string, required except for hidden | Label text. |
placeholder | string | Placeholder text. |
helperText | string | Hint text between the label and the control. |
defaultValue | any | Initial value. See Defaults. |
show | condition[] | Visible when all conditions match. |
showAny | condition[] | Visible when at least one condition matches. |
validation | validation | Validation rules. |
options | { value: string, label: string, image?: string, exclusive?: boolean, pinned?: boolean, description?: string, disabled?: boolean | condition[] }[] | Choices for select, radio, multiselect and autocomplete. Anchor labels for scale and rating. |
randomize | boolean | Shows the options in a random order per respondent. See Option order. Added in 1.6. |
layout | "stack" or "inline" | Option layout for radio and multiselect. stack (default) lists options vertically. inline places short options side by side. |
columns | integer, 1 to 4 | Cards per row for picture options. |
optionsFrom | string | Name of a renderer options provider. |
optionsDependsOn | string[] | Field keys whose changes reload optionsFrom. |
autoAdvance | boolean | See Auto-advance. |
accept | string | Accepted file types for file. |
multiple | boolean | Keeps a list of files in a file field. See File lists. Added in 1.7. |
rows | number | Row count for textarea. |
mask | string | Input mask. The built-in text, email, phone, number and password inputs use it as the placeholder when placeholder is absent. |
inputMode | text, numeric, decimal, tel, email, url, search | Virtual keyboard hint, applied by the built-in text, email, phone, number and password inputs. |
autocomplete | string | HTML autofill token, such as given-name. See Autocomplete. Added in 1.5. |
readOnly | boolean or condition[] | Shows the value without letting the user change it. See Read-only fields. Added in 1.8. |
props | object | Settings of a custom type. Core ignores it. Renderers pass it unchanged as field.props. Added in 1.2. |
i18n | object | Translation keys for label, placeholder and helperText. |
An option MAY have i18n: { label, description }, an image, exclusive, pinned, and a description and disabled. validation MAY have i18n with keys by rule name.
Field keys MUST be unique on every possible path. Two fields MAY share a key only when they are on route branches that never meet on one path; then the field on the active path owns the value. The constructor throws on any other duplicate. Section keys share this namespace.
Autocomplete
autocomplete is an HTML autofill token, such as given-name, family-name, email, tel, street-address, postal-code, bday, organization, one-time-code or off. It lets browsers and password managers fill the field, as WCAG 2.2 success criterion 1.3.5 requires for personal data. The built-in React and Vue renderers set it as the autocomplete attribute of the input, textarea or select. A renderer MUST NOT guess a token when the field has none.
The value is one token, or tokens separated by spaces: an optional section-* name, then shipping or billing, then for tel, email and impp an optional contact type (home, work, mobile, fax, pager), then the field name. Case and extra spaces do not matter. on and off stand alone.
autocomplete applies to text, email, phone, password, textarea, number, date, select, autocomplete and radio fields, and to custom types. For radio, the renderers set it on each input. The autocomplete type sets off when the field has no autocomplete. It does not change validation. In a group item, the built-in renderers put section-<group key>-<item index> before the token, such as section-guests-1 name, with every character of the key other than a-z and 0-9 written as _<hex code point>_, so that browsers do not fill every item with the same value. on and off stay as written. A token with its own section keeps it after the item section: section-home street-address in item 1 of guests becomes section-guests-1-home street-address.
Line breaks in texts
A \n in a step or section description, a field or group helperText or a statement text starts a new line in the built-in renderers. The text stays plain: there is no HTML or Markdown.
Field types
type is any string. The built-in renderers provide these types:
| Type | Value written by built-in renderers |
|---|---|
text, email, phone, password, textarea, autocomplete, hidden | string |
number | number, or null when the input is cleared |
select, radio | string, the selected option value |
multiselect | string[] of distinct selected option values |
checkbox, switch | boolean |
file | a File, or null; with multiple, a File[] |
date | string YYYY-MM-DD |
datetime | string YYYY-MM-DDTHH:mm, without a timezone |
time | string HH:mm, 24-hour |
scale, rating | integer number, the selected point. See Scale and rating |
A hidden field renders no label and no focusable control. Its value comes from the initial values, then its source, then defaultValue. Its value is text of at most maxLength characters, or 2000 without it. Its conditions, rules and type check work like those of any other field. While it is active, an error under its key is a form-level error: topLevelErrors lists it after the other form-level errors, and the error summary, step error counts and focus skip the field. errors and validate() still list it under its key. Built-in messages for it are wrapped in the hidden message template, which names the field by its label, or by its key when the label is empty. A message set in the definition, such as a string required or patternMessage, and a validator result stay as written. Server errors under its key are handled the same way but are not wrapped. For a hidden field inside a group, see Hidden fields in groups.
A hidden field may have a source: { "query": name } or one of referrer, page, pageTitle, language, timezone, device and country. Any other value is an unknown-source or invalid-type error. A source on another field type is a source-not-applicable warning and is ignored. Renderers resolve sources in the browser after mount, without marking a change, from this context:
| Source | Value |
|---|---|
query | The named URL parameter |
referrer | Origin and path of document.referrer, without query and hash |
page | Origin and path of the page URL, without query and hash |
pageTitle | document.title |
language | navigator.language |
timezone | The IANA time zone name |
device | mobile, tablet or desktop |
country | Supplied by the host, such as a server. Browsers supply none |
A value is used when it is a string that is not empty after trimming. It is cut to the field's maxLength, or 2000 characters without it. Otherwise, or when reading it throws, the source yields nothing and defaultValue stays. A key present in the initial values with a value other than "" or null is not resolved. The resolved value is also the value a hidden field gets back when its conditions match again. reset() and Skip drop resolved values, and renderers resolve again only when they mount or get a new definition. With keepValues, a renderer resolves the sources of a new definition only for fields that hold no value.
Any other string is a custom type. A renderer provides its component through its components option and passes it the whole field, so the component reads its settings from field.props. The built-in React and Vue renderers show an "Unsupported field type" placeholder for a type without a component. Core runs type checks for built-in types (see Validation) and treats an unchecked checkbox or switch (false) as empty for required. It does not interpret custom types.
Built-in type names are single lowercase words without separators. A type name with - or :, such as x-rating, acme-rating or acme:rating, is reserved for custom types and never becomes a built-in type. A custom type without - or : can collide with a built-in type added in a later minor version, which then applies its type checks to the field.
File lists
A file field with "multiple": true keeps a list of files. multiple takes effect only in a definition that declares formatVersion 1.7 or newer. multiple on another type is a multiple-not-applicable warning, and a value that is not a boolean is an invalid-type error.
json
{
"formatVersion": "1.7",
"id": "expenses",
"title": "Expenses",
"submit": { "label": "Send" },
"fields": [
{ "key": "receipts", "type": "file", "label": "Receipts", "accept": "image/*,.pdf", "multiple": true, "validation": { "required": true, "maxLength": 5 } }
]
}- Value. An array. The built-in renderers write a
File[]in the order the user added the files, and[]after the user removes the last one. The value of afilefield withoutmultiplestays oneFileornull. - Empty.
[]andnullare empty, sorequiredneeds at least one file. - Count.
validation.minLengthandmaxLengthcount the files and use theminItemsandmaxItemsmessages. A list holds at mostmaxLengthfiles, rounded down and at least 0, or 100 without it, and never more than 1000. A longer list fails withmaxItemsand that number. The corpus filefile-multiple-limits.jsonpins the rounding. - Single values. In the engine, a value that is not an array, such as a reference the app supplied, counts as a list of that one value, and
nullor''as an empty list. Validators receive the list. The engine submits the value as given. - Server.
validateSubmission()checks the value as a list of string references: an array of non-empty strings of at most 10,000 characters each, within the count above. It reads a single string as a list of one, so a renderer that keeps one file, such as@formhaus/react1.6, still submits. Any other value fails with thefilemessage and is dropped. - Renderers. The built-in React and Vue renderers show the file picker and, below it, one row per item, each with a Remove button. A
Fileshows its name. A string the app supplied, such as an upload reference or afile:URL, shows its last path segment as plain text, ignoring trailing/characters, or the whole string when that segment is empty: the renderers never link to it, open it or fetch it, and keep it in the value. An item of another kind gets no row. The button shows theremoveItemlabel, and its accessible name is theremoveItemNamedlabel with the shown name asitem. After a removal, focus moves to the next Remove button, to the previous one after the last file, or to the picker when no file is left. - Picker limit. Picking adds files at the end of the list until it holds the maximum count above, counting every item. Files past it are dropped. The picker is disabled while the list is full, and after a pick that fills it, focus moves to the last Remove button. A status region announces the
itemAddedlabel with the added file names, joined with,, asitem, and, when files were dropped, the field'smaxItemsmessage: itsmaxLengthMessage, else the message catalogs, withmax. The two join with a space, and the renderers also show themaxItemsmessage under the list until the next removal. A removal announcesitemRemoved. Native renderers pass the remaining count to the system picker where it takes one. - Recall. A
{{key}}token shows the list of file names. - Cloud. The Cloud uploader uploads each
Fileof the list and submits the list of upload ids in the same order.
The corpus file file-multiple.json and the scenarios in scenarios/file-multiple.json pin these rules.
Read-only fields
A field MAY have readOnly: true, or a list of conditions that must all match, evaluated like show. An empty list is never read-only.
json
{
"formatVersion": "1.8",
"id": "account",
"title": "Account",
"submit": { "label": "Save" },
"fields": [{ "key": "accountId", "type": "text", "label": "Account ID", "readOnly": true }]
}- Value. A read-only field keeps its value from the initial values,
defaultValue, itssourceorsetValue(). The engine submits it like any visible value. The user cannot change it. - Validation.
readOnlychanges nothing in validation. A read-only field runs every rule like any other field, invalidate(), on Continue, invalidateFieldValue()and invalidateSubmission(), so a stored value that breaks a rule fails and the user cannot fix it. - Server.
readOnlyis not a server guarantee: a client can send any value, andvalidateSubmission()checks it like any other field. An app that needs a fixed value writes it on the server. - Renderers. The built-in renderers draw the control read-only, not disabled, so it stays focusable and its text can be copied. Text, number, date and time inputs get the
readonlyattribute; other controls getaria-readonly="true"and ignore changes. Radio, scale and rating fields put it on the group, which getsrole="radiogroup". The rendererreadOnlyprop makes every field read-only and hides the group Add, Remove and Move buttons. It does not change validation. readOnlythat is not a boolean or a list of conditions is aninvalid-typeerror. Its conditions are checked likeshowconditions.
Scale and rating
scale and rating ask for one point on a numeric range. The built-in renderers draw scale as a row of numbered boxes and rating as a row of stars.
- Range. For
scale, the points run fromvalidation.mintovalidation.max.mindefaults to 1 andmaxto 5. We recommendmin0 or 1 and 3 to 11 points; this is advice, not a check. Forrating, the stars run from 1 tovalidation.max, which defaults to 5. We recommend 3 to 10 stars. Bounds that are not integers, or a range of fewer than 2 or more than 11 points, are aninvalid-scaleerror:ratingmaxmust be 2 to 11. - Value. An integer number of the range, such as
7. Built-in renderers write a number. Core does not convert a numeric string in the browser;validateSubmission()converts a decimal string, such as"7", to a number before the checks, as it does fornumber. - Empty. Like any field:
undefined,nullor''.0is a value, so0on a 0-based scale passesrequiredandnotEmpty. - Type check. A value that is not an integer of the range fails with the
optionmessage.7.5,11on a 0 to 10 scale,"7"in the browser andtrueall fail. required. Works as on any field.minandmaxonscale. They define the range. A value outside it fails the type check, sominMessageandmaxMessagenever show.minandmaxonrating.maxdefines the range.minis an ordinary rule: a rating below it fails with theminmessage, such asMust be at least 3.defaultValue. A point of the range. Another value fails validation like any other value.minLength,maxLength. Do not apply.checkDefinition()warns withrule-not-applicable.- Anchors.
optionsare optional anchor labels. An anchorvalueis the point number as a string, such as"0", and itslabelis the text. Renderers show the labels of three points: the first point at the start, the last point at the end and the middle point,floor((min + max) / 2), in the center. Labels on other points are not shown. Anchors are not choices: core does not check values against them, andcheckDefinition()does not compare condition values with them. - Conditions.
eq,neq,inandnotIncompare numbers, andgt,gte,ltandltecompare the point.checkDefinition()warns about a string operand withcondition-value-mismatch. - Keyboard. Each point is a native radio. Arrow keys move between points. Digit keys 0 to 9 select the point with that number; on a range that ends at 10 and starts at 1,
0selects 10.
An NPS question is a scale from 0 to 10 with two anchors. Branch on detractors with lte: 6 and on promoters with gte: 9:
json
{
"formatVersion": "1.3",
"id": "nps",
"title": "NPS",
"submit": { "label": "Send" },
"fields": [
{
"key": "score", "type": "scale", "label": "How likely are you to recommend us to a friend?",
"validation": { "required": true, "min": 0, "max": 10 },
"options": [{ "value": "0", "label": "Not at all likely" }, { "value": "10", "label": "Extremely likely" }]
},
{ "key": "fix", "type": "textarea", "label": "What should we fix first?", "show": [{ "field": "score", "lte": 6 }] },
{ "key": "love", "type": "textarea", "label": "What do you like most?", "show": [{ "field": "score", "gte": 9 }] },
{ "key": "stars", "type": "rating", "label": "Rate the support you got", "validation": { "max": 5 } }
]
}Options
options is a static list. optionsFrom names an options provider passed to the renderer. Built-in renderers call the provider with all current values, and again each time a field in optionsDependsOn changes. The returned options replace options. Core checks that a select, radio or multiselect value is one of the static options. It skips that check when optionsFrom is set, so the app validates dynamic lists itself. Core does not read optionsDependsOn.
Picture options
An option of a radio or multiselect field MAY have image, the URL of a picture. The built-in renderers show it above the label and place the options in a grid. The label stays required and visible, and it names the option for assistive technology, so the image has an empty alt. The value is the option value, as for any option. select and autocomplete ignore image. Images load from the URL as given; a strict Content Security Policy needs img-src for its host. The image host sees the respondent's IP address. The built-in renderers send no Referer header with option images. An image that does not start with https: or data:image/ is an unsafe-image-url warning. The built-in renderers draw no image for a URL with a scheme other than https:, http:, blob: or a png, jpeg, webp or gif data:image/, or with credentials before the host. Relative URLs are drawn. Renderers SHOULD bound the download size and decoding cost of an option image. The web renderers rely on the browser's limits. The native ports fetch at most 10 MB per image and draw no image larger than 2048 pixels on a side.
columns sets the number of cards per row, from 1 to 4. Without it, the built-in renderers fill the row with cards about 200px wide. On screens narrower than 480px they show at most 2 cards per row. Any other value is an invalid-type or invalid-columns error. columns is a columns-not-applicable warning and is ignored on a field whose options have no image, on a field type other than radio and multiselect, and on a field whose parent container has layout: "matrix". Each card has a button that opens the image at full size.
Exclusive options
An option of a multiselect field MAY have "exclusive": true. It is the only answer when picked, as in "None of these" or "Prefer not to say".
json
{
"formatVersion": "1.5",
"id": "health",
"title": "Health",
"submit": { "label": "Send" },
"fields": [
{
"key": "conditions",
"type": "multiselect",
"label": "Do you have any of these conditions?",
"options": [
{ "value": "asthma", "label": "Asthma" },
{ "value": "diabetes", "label": "Diabetes" },
{ "value": "none", "label": "None of these", "exclusive": true }
]
}
]
}setValue()andsetItemValue()apply the rule against the current value. A new list that adds no value is written as given. A new list that adds an exclusive option becomes a list of that option alone; when it adds several, the last one wins. Otherwise a new list that adds other values and holds an exclusive option drops the exclusive options. Several exclusive options clear each other.- Initial values,
reset()and loaded drafts are not changed. A list with an exclusive option and any other value, including a second exclusive option, fails the type check with theexclusivemessage, invalidate()and invalidateSubmission().validateSubmission()leaves it out of the returned values like any value that fails its type check. The server never picks one for the user. - One exclusive option alone is an answer: it satisfies
required, andminLengthdoes not apply to it.maxLength,contains,notContainsandnotEmptywork as for any list. - The built-in renderers show the
orlabel before the first exclusive option that follows a non-exclusive one. The options stay native checkboxes. In a section withlayout: "matrix"the divider is hidden. exclusiveis ignored on other field types and on a field withoptionsFrom, which reportsexclusive-not-applicable. An exclusive option followed by a non-exclusive one is anexclusive-option-positionwarning, adefaultValuewith an exclusive option and other values isexclusive-default-value, andminLengthgreater than 1 isexclusive-with-min-length.
Option order
A radio, multiselect or select field MAY have "randomize": true. Each respondent then sees its options in their own order, which cancels position bias in surveys. An option with "pinned": true keeps its written position, at the start, in the middle or at the end. An exclusive option is always pinned.
json
{
"formatVersion": "1.6",
"id": "tools",
"title": "Tools",
"submit": { "label": "Send" },
"fields": [
{
"key": "tools",
"type": "multiselect",
"label": "Which tools did you use last month?",
"randomize": true,
"options": [
{ "value": "figma", "label": "Figma" },
{ "value": "sketch", "label": "Sketch" },
{ "value": "framer", "label": "Framer" },
{ "value": "other", "label": "Other", "pinned": true },
{ "value": "none", "label": "None of these", "exclusive": true }
]
}
]
}The order depends only on the engine seed, the order key, the number of options and which of them are pinned. The order key is the field key, and <group key>.<field key> for a field of a group, so all items of a group share one order. Implementations MUST compute the order with integer arithmetic modulo 2^32, as follows:
Hash the UTF-16 code units of
seed + "\u001f" + keywith 32-bit FNV-1a. Start withh = 2166136261. For each code unitc, seth = ((h XOR c) × 16777619) mod 2^32.Seed mulberry32 with
s = h. Each outputuis:s = (s + 0x6D2B79F5) mod 2^32 t = ((s XOR (s >> 15)) × (s OR 1)) mod 2^32 t = t XOR ((t + ((t XOR (t >> 7)) × (t OR 61))) mod 2^32) u = t XOR (t >> 14)Take the indexes of the unpinned options in written order. For
ifromn - 1down to1, take the nextu, setj = u mod (i + 1)and swap the entries atiandj. Put the result back into the unpinned positions.
The conformance corpus file option-order.json lists vectors of seeds, keys and orders.
@formhaus/coreapplies the order through the opt-in research module,@formhaus/core/research. Without it, options show in written order.- The seed is the
seedengine option or, without it, 16 random bytes as hex. It does not change for the life of the engine, so the order stays the same across re-renders, Back,goToStep(),reset(), visibility changes andreplaceDefinition(). A new engine shows a new order unless the host passes the same seed. - Values, defaults, conditions, validation and the submit payload do not change.
validateSubmission()ignoresrandomize. - The order is not applied to other field types, to a field in a section with
layout: "matrix", or when fewer than two options are unpinned.randomizeon another type or in a matrix section, andpinnedon a field withoutrandomize, arerandomize-not-applicablewarnings. - The built-in renderers draw the options in the shown order in the DOM, so keyboard and screen reader order match what is seen. A native
selectkeeps its placeholder first. Without aseedoption, they render the written order on the server and during hydration, and the shown order after mount.
Option descriptions and disabled options
An option of a radio, select or multiselect field MAY have description, a short text shown under its label, and disabled: true, or a list of conditions that must all match. Inside a group, the conditions read the fields of the same item first, like show. An empty list never disables.
json
{
"formatVersion": "1.8",
"id": "workspace",
"title": "Workspace",
"submit": { "label": "Save" },
"fields": [
{ "key": "seats", "type": "number", "label": "Seats" },
{
"key": "plan",
"type": "radio",
"label": "Plan",
"options": [
{ "value": "starter", "label": "Starter", "description": "Up to 5 seats", "disabled": [{ "field": "seats", "gt": 5 }] },
{ "value": "pro", "label": "Pro", "description": "Any number of seats" },
{ "value": "legacy", "label": "Legacy", "disabled": true }
]
}
]
}- Description. A translatable text with the address
fields.<key>.optionDescriptions.<value>and the translation keyi18n.description. The built-in renderers show it under the option label and point the option'saria-describedbyat it. Aselectshows no description. Option descriptions do not recall answers. - Disabled option. The built-in renderers draw it with the
disabledattribute, so it cannot be picked. It keeps its place, and values, conditions and the submit payload do not change. - Validation. A value that holds a disabled option fails with the
optionmessage, after the type check, unless the stored answer of the field already holds that option. A list fails when any of its options is disabled and not stored. - Stored answer. The field's
defaultValueis always held. In the engine, the other stored answers are the values the engine started with: the initial values,reset(values)and thesourceof a field.validateSubmission()takes them from itspreviousValuesoption, an object of the same shape as the submitted values.previousValuesMUST come from the stored record, never from the request. A respondent can keep a stored answer that is now disabled, or pick it again, but cannot pick a disabled option the field did not hold. - Group items. For an item field, a disabled option is held as many times as it appears in that field across the stored items of the group, counting each value of a
multiselectlist. The current items use these holds in order. A moved or re-added item keeps its option. A new item past the count fails withoption, so a submission cannot copy a held option into more items. The engine andvalidateSubmission()apply the same rule. disabledon an option of another field type is adisabled-not-applicablewarning and is ignored. Adescriptionthat is not a string, or adisabledthat is not a boolean or a list of conditions, is aninvalid-typeerror. Conditions ofdisabledare checked likeshowconditions.
The corpus file option-rules.json, the scenarios in scenarios/option-rules.json and fixtures/submissions/option-rules.json pin these rules.
Sections
A section is a node with type: "section". It groups fields under a title and shares its conditions with them.
json
{
"formatVersion": "1.1",
"id": "order",
"title": "Order",
"submit": { "label": "Order" },
"fields": [
{ "key": "invoice", "type": "checkbox", "label": "I need an invoice" },
{
"key": "billing", "type": "section", "title": "Billing address", "description": "Where we send invoices",
"show": [{ "field": "invoice", "eq": true }],
"fields": [
{ "key": "street", "type": "text", "label": "Street", "validation": { "required": true } },
{ "key": "city", "type": "text", "label": "City" }
]
}
]
}| Property | Type | Meaning |
|---|---|---|
key | string, required | Section identifier for translations, DOM ids and editors. Unique among field and section keys. |
type | "section", required | |
title | string, required | Section heading. |
description | string | Text below the heading. |
show, showAny | condition[] | Section visibility. |
layout | "matrix" | Draws the section as a matrix. Added in 1.3. |
fields | (field or group)[], required | Fields and groups of the section. MAY be empty. |
i18n | object | Translation keys for title and description. |
A section holds no value. A condition that names a section key is an unknown-field error. A section MAY appear in step.fields and in single-step fields, and never spans steps. A section MUST NOT contain another section.
A field inside a section is visible when the conditions of the section and its own conditions pass. Section conditions follow the rules of field conditions. A section condition on a field inside the same section is a condition-cycle error. When a section is hidden, its fields and groups are cleared like fields hidden by their own conditions.
Fields inside a section keep their keys. The submit payload does not change when a field moves into or out of a section.
A section MAY have an empty fields array. It then shows only its title and description, as a statement between questions.
Matrix
layout: "matrix" draws a section as a grid, also called a Likert table. Each field of the section is a row, and the options of the first field are the column headers. Use radio rows, or multiselect rows for several answers per row, with the same options in the same order. A row whose option values differ is a matrix-options-mismatch warning. Values stay flat: each row writes its own key, and conditions, rules and the payload treat a row like any other field. Do not set autoAdvance on a row: answering one row would leave the step. A renderer that does not know layout draws a plain section of the same fields.
json
{
"formatVersion": "1.3",
"id": "pulse",
"title": "Team pulse",
"submit": { "label": "Send" },
"fields": [
{
"key": "agree", "type": "section", "layout": "matrix", "title": "How much do you agree?",
"fields": [
{
"key": "goals", "type": "radio", "label": "The goals of my team are clear", "validation": { "required": true },
"options": [{ "value": "1", "label": "Disagree" }, { "value": "2", "label": "Neutral" }, { "value": "3", "label": "Agree" }]
},
{
"key": "heard", "type": "radio", "label": "My opinion is heard",
"options": [{ "value": "1", "label": "Disagree" }, { "value": "2", "label": "Neutral" }, { "value": "3", "label": "Agree" }]
}
]
}
]
}Groups
A group is a node with type: "group". Its value is an array of items. Each item is an object keyed by the keys of the group fields.
json
{
"formatVersion": "1.1",
"id": "registration",
"title": "Registration",
"submit": { "label": "Register" },
"fields": [
{
"key": "participants", "type": "group", "label": "Participants",
"itemLabel": "Participant {index}", "addLabel": "Add participant", "removeLabel": "Remove",
"defaultItems": 1,
"validation": { "required": true, "maxLength": 5 },
"fields": [
{ "key": "name", "type": "text", "label": "Name", "validation": { "required": true } },
{ "key": "email", "type": "email", "label": "Email", "validation": { "required": true } },
{ "key": "diet", "type": "select", "label": "Diet", "options": [{ "value": "none", "label": "None" }, { "value": "other", "label": "Other" }] },
{ "key": "dietNote", "type": "text", "label": "Details", "show": [{ "field": "diet", "eq": "other" }] }
]
}
]
}| Property | Type | Meaning |
|---|---|---|
key | string, required | Key of the item array. Unique like a field key. |
type | "group", required | |
label | string, required | Group heading. |
helperText | string | Text below the heading. |
itemLabel | string | Item heading. {index} is the item number, starting at 1. {label} is the group label. Default: the itemLabel label. |
addLabel, removeLabel | string | Texts of the Add and Remove buttons. Defaults: the addItem and removeItem labels. |
defaultItems | integer | Number of items the group starts with, at most maxLength, or 100 without maxLength, and never more than 1000. |
reorderable | boolean | Lets the user move items up and down. See Reordering items. Added in 1.8. |
show, showAny | condition[] | Group visibility. |
validation | required, minLength, maxLength, their messages, validator | Item count rules. |
fields | field[], required | Fields of one item. |
i18n | object | Translation keys for label, helperText, itemLabel, addLabel and removeLabel. |
Rules:
- A group MAY appear in
step.fields, in single-stepfieldsand in a section. A group MUST NOT contain a section, another group or afilefield, and below format 1.9 ahiddenfield. The constructor throws on them (invalid-nesting). - Item keys MUST be unique inside the group and MUST NOT repeat a field or section key outside it. No other key MAY start with the group key followed by
., because error paths use that form. The constructor throws on these (duplicate-key). Two groups MAY use the same item keys. - A condition or
matchFieldof an item field MAY use the other fields of the same item, evaluated per item, and fields outside the group under the rules of field conditions. A condition,matchFieldoroptionsDependsOnoutside the group MUST NOT use item fields (group-scope). It MAY test the group itself, such as withnotEmpty. required: truemeans at least one item.minLengthandmaxLengthcount items, not characters, and use theminItemsandmaxItemsmessages. Like other rules,minLengthdoes not apply to an empty group.
A new item, from defaultItems or Add, holds the defaultValue of its fields. An item in the initial values or in reset(values) gets the defaultValue of the fields it does not have, like top-level fields. setValue() of the group stores its items as given. Their start values are the written values, and the defaultValue of each field an item does not have. A group holds at most 1000 items, whatever its maxLength. Its item limit is maxLength, or 100 without maxLength, capped at 1000. Built-in renderers hide Add when the group has as many items as its limit, and hide Remove when it has minLength items, or 1 when required. defaultItems creates no more items than the limit: a group with defaultItems: 1000000 and no maxLength starts with 100 items, and a group with defaultItems and maxLength both 10000000 starts with 1000 items. The same limit applies on construction, reset(), Skip, Add, replaceDefinition() and in validateSubmission(). A maxLength or defaultItems over 1000 is a group-item-limit warning.
An item field hidden by its conditions is removed from its item, and its error is removed. When it is shown again and holds no value, it gets back its last value in that item, or else the value its item started with. An item starts with the values it has after the initial values or the last reset(), defaults included, or with the defaultValue of its fields when it comes from defaultItems, Add or Skip. Last values are kept per item, so they stay with the item when another item is removed or moved, and removing an item forgets its own.
A hidden group is cleared like a field. A group that becomes visible again gets back its last items, with the same item ids, or else its start value.
Hidden fields in groups
From format 1.9, a group MAY contain hidden fields. They carry item data the user does not edit, such as a stored id.
json
{
"formatVersion": "1.9",
"id": "team",
"title": "Team",
"submit": { "label": "Save" },
"fields": [
{
"key": "members",
"type": "group",
"label": "Members",
"fields": [
{ "key": "id", "type": "hidden", "label": "Member id", "defaultValue": "new" },
{ "key": "name", "type": "text", "label": "Name" }
]
}
]
}- Its value in an item comes from the item in the initial values, or from its
defaultValuewhen the item does not have it or comes fromdefaultItems, Add or Skip. - The value is part of its item: it moves with the item on
moveItem(), is removed with it onremoveItem(), and is submitted in it. - It renders no label and no visible control, like a top-level
hiddenfield. An item that holds onlyhiddenvalues has no content for the remove confirmation. - Its conditions, rules and type check work like those of a top-level
hiddenfield, per item. Its value is text of at mostmaxLengthcharacters, or 2000 without it, and built-in messages are wrapped in thehiddenmessage template. - While its item field is active, an error under its item path is a form-level error:
topLevelErrorslists it with the errors of top-levelhiddenfields, in field order and item by item, and the error summary, step error counts and focus skip the field.errorsandvalidate()still list it under its path. A server error under its path is handled the same way and does not open its step. - When its item conditions match again, it gets back the value its item started with, never its last value.
- A
sourceon it is asource-in-grouperror. - Unsaved changes report it by item path.
validateSubmission()returns it in its item after the type check and rules, like any item field. It drops the value when the item conditions hide the field, unlesshiddenValuesis"keep". The client sets every value, so the server MUST NOT trust ahiddenitem value it did not write.
validateSubmission() rejects a group value with more items than maxLength with the maxItems message, and a value that is not an array of plain objects, or that has more items than its item limit (100 without maxLength, at most 1000), with the value message. It does so before checking any item and leaves the value out of the returned values. It drops unknown item keys, runs the type checks and rules of every visible item field, and reports item errors by path.
Error paths
Editing an item field keeps the error under the group key; adding, removing or replacing items clears it. Errors of item fields use the path <group>.<index>.<field>, with a 0-based index, such as participants.1.email. Count rules and the group validator use the group key. errors, stepErrors, validate(), setErrors() and server errors use these paths. When an item is removed or moved, the errors of the items it passes move to their new index.
Engine operations
| Method | Meaning |
|---|---|
addItem(key) | Adds an item. Returns false at the maximum or when the group is not visible. |
removeItem(key, index) | Removes an item. Returns false at the minimum or for an index out of range. |
moveItem(key, from, to) | Moves the item at from to to. Returns false when the group is not visible, an index is out of range or from equals to. |
setItemValue(key, index, field, value) | Writes one item field. setValue('<group>.<index>.<field>', value) does the same. |
setValue(key, items) | Replaces the whole array. |
items(key) | The items of a visible group: a stable id for rendering and the visible item fields. |
Reordering items
moveItem(key, from, to) takes the item out at from and inserts it at to, both 0-based. The item keeps its values, its id, the last values of its hidden fields and its stored answers. Its errors, server errors and loading states move with it, and those of the items between from and to shift by one. It writes the group like setValue(key, items): it clears the error under the group key and emits no form event of its own.
A group with "reorderable": true lets the user move items. Renderers that support it show Move up and Move down buttons on each item, with the moveUp and moveDown labels, and announce the itemMoved label with the item title as item and its new 1-based position as position. In @formhaus/react and @formhaus/vue the buttons are opt-in, from the reorder entry; without it, a reorderable group works without them and logs a warning in development. reorderable that is not a boolean is an invalid-type error.
The scenarios in scenarios/move-item.json pin these rules.
Conditions
A condition tests the value of one field:
| Property | Type | Matches when |
|---|---|---|
field | string, required | Key of the field to test. |
eq | string, number or boolean | value === eq |
neq | string, number or boolean | value !== neq |
in | (string or number)[] | the list contains the value |
notIn | (string or number)[] | the list does not contain the value |
contains | string, number or boolean | the value is an array with an item === contains. Added in 1.4 |
notContains | string, number or boolean | contains with the same operand does not match. Added in 1.4 |
notEmpty | boolean | true: the value is not empty |
gt | number | the numeric value > gt |
gte | number | the numeric value >= gte |
lt | number | the numeric value < lt |
lte | number | the numeric value <= lte |
A condition MUST use exactly one operator. The constructor throws on a condition with no operator, with several operators, or with a key that is not an operator. At runtime, a condition without a known operator never matches. notEmpty: false always matches; checkDefinition() warns about it with condition-always-true.
Comparison is strict and without type coercion: "1" does not equal 1. in and notIn test the value itself, so an array value never matches in. contains and notContains test the items of an array value, such as a multiselect answer. contains never matches a value that is not an array, including an unanswered field, so notContains matches it. false and 0 count as not empty for notEmpty. in: [] never matches; notIn: [] always matches.
For gt, gte, lt and lte, the numeric value is the value itself when it is a finite number, or Number(value) when it is a non-empty string that converts to a finite number. Any other value, including an empty one, does not match.
Combining conditions
An object with show and showAny is visible when:
- every condition in
showmatches, and showAnyis absent or empty, or at least one of its conditions matches.
An empty show array always passes. An empty showAny array is treated as absent. The same rule applies to steps and routes.
Visibility
Every condition sees the active projection: the values of visible fields on the steps of the active path before the current one, plus the values of its own step. Field, step, route and action conditions use the same rule, with or without routes. In a single-step form, the projection is the values of the visible fields.
A field condition MUST reference a field of the same or an earlier step. A step condition MUST reference a field of an earlier step. The constructor throws on a condition that references a later step or a key that is not a field key. Values for keys that are not field keys, such as extra initial values, are never in the projection.
A field is visible when its own conditions pass, the conditions of its section pass and, in a multi-step form, its step is on the active path. An item field is visible when its group is visible and its conditions pass against the active projection plus the values of its own item.
Core clears the value of a field hidden by conditions. The key is removed from engine.values and its error is removed. Clearing runs when the engine is constructed, after reset() and replaceDefinition(), after every setValue() and after Skip, so a value written to a field hidden by conditions is cleared at once. It cascades: if a cleared value hides another field or step, that value is cleared too. Every field of a step hidden by its own conditions is cleared.
A field that becomes visible and holds no value gets back its last value: the value it held when it was hidden, or the last value written to it while hidden. '', null, false and undefined are last values too, so an unchecked preselected checkbox comes back unchecked and a cleared field comes back cleared.
A field without a last value gets its start value: its value in the initial values of the constructor or the last reset(), or else its defaultValue. This covers a field that starts hidden, such as a field on a step shown by an earlier answer. A restored value can show or hide other fields, which are then updated in the same way.
Last values live in the engine. reset() and replaceDefinition() forget them, and Skip forgets those of the step it resets. A new engine, such as one that reopens a draft through initialValues, starts without them.
A field of type hidden always gets back its start value, never its last value. Its start value also includes its resolved source, after the initial values and before defaultValue.
In a form with routes, fields on steps that are off the active path keep their values. See Routes.
Fields hidden by conditions are not validated and not submitted, unless hiddenValues is "keep" (see Kept hidden values). For groups, see Groups.
Kept hidden values
The engine option hiddenValues is "clear" (default) or "keep". With "keep", the engine clears and restores values internally as above, and adds back to engine.values the value each field hidden by conditions would get when shown again: its last value or start value. The same applies to item fields hidden in their item and to fields of hidden groups, sections and steps. The submit payload then also holds these values, trimmed, and the values of fields off the active path. It still leaves out fields of skipped steps and keys that are not field keys.
Conditions, validation, validators and recall see the same values as with "clear": a hidden field is unanswered and has no error. Hooks that receive the payload, such as the submit handler, onBeforeSubmit, onAfterSubmit, the step change hooks and onStepValidate, get it with the kept values.
validateSubmission() takes the same option. With "keep", it returns the values of hidden fields and of fields off the active path, after trimming and number conversion. It checks each of them against every rule of its field except required, as for a visible field, and drops one that fails without an error. For a group, it checks the group and each item field. The client decides which fields are hidden, so a kept value is as untrusted as a visible one. The scenarios in hidden-values.json and the corpus file hidden-values.json pin this rule.
Revealed fields
Renderers MAY draw a field under the option that shows it, as GOV.UK and USWDS do with conditional reveals. This changes only the layout. Visibility, values, validation, the submit payload and the order of errors stay as described above. The rule reads the definition only, never values, and applies to each node list on its own: fields of a form without steps, fields of each step, and fields of each section without layout: "matrix".
A node C of a list is revealed by option k of a node F earlier in the same list when:
Fis a field of typeradioormultiselectwith a non-emptyoptionslist, nooptionsFrom, nolayout: "inline"and no option withimage.Cis a field that is not a section, a group or ahiddenfield, and has exactly one condition inshowandshowAnytogether. That condition namesFby key. Its operator, chosen as in Conditions, iseqfor aradioandcontainsfor amultiselect, and its operand is===thevalueof optionk.- Every node between
FandCmeets rule 2 forFtoo. The first node that does not ends the run ofF. - For a
multiselect, the option indexes along the run never go down, and withrandomizethey are all the same. The first node that breaks this ends the run. - A node already revealed by an earlier
Fkeeps that parent.
A revealed field can be a choice field with a run of its own, so reveals can nest. Rule 4 keeps the fields in written order on screen: a radio shows the fields of one option at a time, and the fields of a multiselect follow its options. A renderer draws C in place when F is not shown, and keeps the fields of a group item in place. revealTargets(nodes) in TypeScript returns, for each node of a list, { parent, option } with the index of F in the list and k, or null. The corpus file reveal.json pins this rule.
Defaults and initial values
When the engine is constructed or reset, values are built in this order:
defaultValueof every field that has one.- The initial values passed to
new FormEngine(definition, initialValues)orreset(values). They override defaults. - Fields hidden by conditions are cleared. They keep the result of steps 1 and 2 as their start value and get it back when they are shown. See Visibility.
An initial value of null or '' is a start value too, so the field does not fall back to defaultValue.
Initial values for keys that do not belong to any field stay in engine.values but are not submitted.
Replacing the definition
engine.replaceDefinition(definition) switches a running form to a new definition and keeps the answers that still fit. The renderers call it when the definition prop changes and keepValues is set. Without keepValues, a new definition object still starts a new form.
- The new definition is checked like in the constructor. On an error,
replaceDefinition()throwsFormDefinitionErrorand the engine stays unchanged. - A value is kept when a field with the same key and the same
typeexists in both definitions. Values of fields whosetypechanged, of removed fields and of keys that belong to no field are dropped. - Values are then built as on construction, with the kept values as initial values: new fields get their
defaultValueordefaultItems, kept group items keep their ids and the values of item fields with the same key andtype, other item fields get theirdefaultValue, and fields hidden by conditions are cleared. Kept values are start values. Last values from before the replacement are forgotten. - A field error or server error stays when its field is visible on the new active path and its
typedid not change. An item field error also needs the item field to keep its key andtype, and follows the rules of Groups. Form-level errors stay. - The current step stays when its id is on the new active path, at its new position. Otherwise core moves to the nearest earlier step of the old path that is on the new path, or to the first step. Steps inserted before the current step do not move it. Submit validates them and opens the first step with an error.
- A skipped step stays skipped while the new definition has a step with its id. Its fields are the fields of the new step.
- Pending navigation and pre-submit results are discarded, as with
cancelPendingActions(). A response to a submission already sent is ignored. See Concurrent submissions. - After
start(), the engine reportsstep_viewedwhen the current step changes, andfield_shownorfield_hiddenfor conditional fields of both definitions whose visibility changed. It does not reportform_reset.
Validation
validation holds these rules:
| Rule | Type | Applies to | Default message |
|---|---|---|---|
required | boolean or string | any value | This field is required |
minLength | number | string length; item count of a multiselect, a group or a file list | Minimum length is N; At least N required for arrays |
maxLength | number | string length; item count of a multiselect, a group or a file list | Maximum length is N; At most N allowed for arrays |
min | number | number values; the range of a scale; the lowest rating of a rating | Must be at least N |
max | number | number values; the range of a scale or rating | Must be at most N |
pattern | string | String(value) | Invalid format |
matchField | string | any value | Fields must match |
validator | string | any value | message returned by the validator |
Each rule except required and validator has a matching message property: minLengthMessage, maxLengthMessage, minMessage, maxMessage, patternMessage, matchFieldMessage. A string required is its own message. Without one, the message comes from the catalogs.
Core evaluates one field as follows and returns the first error:
- If the value is empty, return the
requirederror whenrequiredistrueor a non-empty string. Otherwise, return thematchFielderror when the named field has a non-empty value, or no error. No other rule runs. For validation, empty also includesfalseforcheckboxandswitch. - The type check for built-in types other than
file:emailwith a top-level domain and at most 254 characters,dateas a real calendar dateYYYY-MM-DD,datetimeasYYYY-MM-DDTHH:mmwith optional seconds, milliseconds and aZor±HH:mmoffset, and a real calendar date,timeas 24-hourHH:mmwith optional seconds from00:00to23:59:59, a finite number fornumber, an integer of the range forscaleandrating, a boolean forcheckboxandswitch, a static option value forselect,radioandmultiselectwithoutoptionsFrom, an array without repeated values and without an exclusive option next to other values formultiselect, and at most 10,000 characters (ormaxLength) for strings. Custom types skip it. - A value that holds a disabled option the stored answer does not hold fails with the
optionmessage. - For a string or array:
minLength, thenmaxLength. For a number:min, thenmax. Other value types skip these rules. A numeric string is not converted. pattern, compiled withnew RegExp(pattern)without flags and without implicit anchors. An invalid pattern is a definition error, so the constructor throws on it. A value longer than 10,000 characters failspatternwithout being matched. One validation matches at most 10,000 values against patterns: eachvalidate(), each step check on Continue, eachvalidateFields()call and eachvalidateSubmission()call counts from zero. Values are matched in validation order: the fields of each step on the active path in definition order, and the items of a group, item by item, right after the group field. After 10,000 matches,patternfails without matching, so the field gets itspatternerror. The limit bounds the work of one request with many fields, items and patterns. The engine andvalidateSubmission()run every pattern thatcheckDefinition()reports asslow-pattern; the report is only a warning.matchField: the value is compared with===to the value of the named field. A field on a skipped step has no value here. In a form with routes, a field off the active path has no value either.validator: the named function from thevalidatorsoption is called with the value and the values thatmatchFielduses. A non-empty string result is the error;nullor''is no error, andvalidateField()returnsnullfor both. An unregistered name is ignored at runtime, and the constructor logs a warning for it. The validator never receives an empty value, because step 1 returns first.
Validation runs on Continue for the visible fields of the current step, and on Submit for the visible fields of every non-skipped step on the active path. A group runs its count rules first, then the rules of the visible fields of every item, with the values of the same item in place of matchField and validator values. Renderers do not validate on blur. When Submit fails validation, the engine moves to the earliest step with an error. Like setErrors(), this move does not run the step change hooks. After a failed Continue or Submit, built-in renderers focus the invalid field when the error summary lists one error. When it lists two or more, they focus the error summary, which has tabindex="-1" and role="alert", and scroll it into view. With errorSummary off, they focus the first invalid field.
Steps
| Property | Type | Meaning |
|---|---|---|
id | string, required | Step identifier. |
title | string, required | Step heading. |
description | string | Text below the heading. |
fields | node[], required | Fields, sections and groups of the step. |
show, showAny | condition[] | Step visibility. |
routes | route[] | Ordered forward destinations. |
next | action or false | Continue action. |
back | action or false | Back action. |
skip | action | Skip action. See Skip. |
i18n | object | Translation keys for title and description. |
Step ids MUST be unique. The constructor throws on duplicates.
A step MAY have an empty fields array. It then shows only its title, description and actions, as a welcome screen or a statement. Set next to label its button, such as { "label": "Start" }. Continue on it always succeeds. It counts toward progress, so a welcome step makes "Step 1 of N" one step longer.
json
{
"formatVersion": "1.3",
"id": "welcome",
"title": "Feedback",
"submit": { "label": "Send" },
"steps": [
{ "id": "intro", "title": "Tell us about your stay", "description": "It takes two minutes.", "fields": [], "next": { "label": "Start" } },
{ "id": "rate", "title": "Your rating", "fields": [{ "key": "stars", "type": "rating", "label": "Rate your stay", "autoAdvance": true }] },
{ "id": "comment", "title": "Anything else?", "fields": [{ "key": "comment", "type": "textarea", "label": "Comment" }] }
]
}A step hidden by conditions is left out of navigation, progress, validation and submission, and its field values are cleared.
Step show/showAny MUST reference fields of earlier steps. A step condition sees only the values of earlier steps on the path.
Opening a step by id
goToStep(stepId) opens a step for URL routing and browser history. A step is reachable when it is on the active path and every step between the current step and it is valid or skipped. Valid means that the visible fields of the step pass their client rules, as on Continue. A step at or before the current step is always reachable, like Back. goToStep does not show errors, does not run onStepValidate or the step change hooks, and does not skip or include steps.
When the target is not reachable, the engine opens a fallback step and returns why:
reason | Target | Fallback |
|---|---|---|
blocked | A step on the active path behind an invalid step, or any step while a step change or submission is pending | The first invalid step between the current step and the target, or the current step while an action is pending |
not-on-path | A step of the definition that conditions or routes leave out of the active path | The last reachable step on the active path that comes before the target in the definition |
unknown-step | An id that no step has, or any id in a form without steps | The current step |
The result is { stepId, reached: true } or { stepId, reached: false, reason }, where stepId is the step that is now current, or null in a form without steps. When the target is not reached, the engine reports step_redirected with requestedStepId, stepId and reason. A step change reports step_viewed, not step_completed.
Actions
An action is an object:
| Property | Type | Meaning |
|---|---|---|
label | string, required | Button text. |
variant | primary, secondary, text | Button style. |
disabled | condition[] | Disabled when all conditions match. |
i18n | object | Translation key for label. |
The five action slots are:
submitreplaces Continue on the last step of the active path, and is the only primary action of a single-step form.nextsets the Continue label.next: falsehides Continue on that step. It does not block navigation, and it never hides Submit on the last step. Renderers do not show Skip on a step withnext: false.backsets the Back label.back: falsehides Back. Back never appears on the first step.skipshows a Skip action on that step.cancelshows a Cancel action that calls the renderer's cancel handler. Core has no cancel operation.
Built-in renderers draw Continue and Submit as primary, Back as secondary, and Skip and Cancel as text buttons. variant changes the style of back, skip and cancel; built-in renderers ignore it on submit and next. Built-in renderers evaluate disabled on submit and on next, against getSubmitValues(). With hiddenValues: "keep", they leave the kept values out. They ignore disabled on back, skip and cancel, and checkDefinition() warns about it with disabled-not-applicable. Values of fields off the active path and of skipped steps do not count. An empty disabled array never disables. Default labels are Continue, Back, Skip and Submit. The continue and back labels replace the Continue and Back defaults. In built-in renderers, Enter in a single-line input runs the primary action.
Routes
A route is { "to": string | null, "show"?: condition[], "showAny"?: condition[] }. Routing is enabled for the whole form when at least one step has a non-empty routes array. Without routes, the active path is every visible step in declaration order.
Rules enforced by the constructor:
toMUST be the id of a later declared step, ornull. Unknown, self and backward targets throw. Because every target is a later step, routes cannot form cycles.- Route conditions MUST reference fields of the same step or an earlier step.
Route selection on a step:
- Routes are tried in order. A route matches when its conditions pass and its target step is visible. A route to a step hidden by conditions is passed over.
- The first match wins. A route without conditions always matches, so it serves as a fallback when it is last.
- A matching
to: nullmakes this step the last step of the path. Submit appears there. It does not submit the form. - If no route matches, the path continues with the next declared step.
Branches converge only through routes. A branch step without an exit route falls through to the next declared step, which may be a sibling branch. checkDefinition() warns when a route target has no unconditional route and the next declared step is another target of the same step.
Active path
Core computes the active path from the first declared step, with or without routes:
- Start with an empty set of path values.
- A step whose
show/showAnyfails against the path values of earlier steps is passed over and the next declared step is tried. - A visible step joins the path. Its visible fields with defined values are added to the path values. Field conditions in that step see the earlier path values and every value of the same step.
- The next step comes from route selection, evaluated against the path values. Without routes, it is the next declared step.
The path values are the active projection. Route conditions, step conditions, field visibility, action disabled, validation, lifecycle hooks and submission use the active projection, not engine.values. Values of fields on steps off the path stay in engine.values, so returning to a branch restores them, but they cannot select a route or enter the payload.
When a value change removes the current step from the path, core moves to the nearest earlier step of the old path that is still on the new path. Back moves to the previous step of the current path.
Skip
Skip on a step with skip (skip() returns false on a step without it):
- Resets the step's fields to their
defaultValue, or removes them when there is none, and removes their errors. Fields hidden by conditions are cleared after the reset, so a default of a field that the reset values hide is removed too. ThedefaultValuebecomes the field's start value and its last value is forgotten (see Visibility). When the submit of a final-step Skip is rejected, the values, start values and last values of the step come back. - Marks the step as skipped and moves to the next step of the path computed from the reset values. Skip does not run field validation or
onStepValidate.skip()runsonBeforeStepChangeandonAfterStepChangewithreason: 'skip';falsefrom the before-hook cancels the skip and changes nothing. - A skipped step is excluded from submit validation. Its fields are excluded from the payload and from the values that validation and lifecycle hooks receive.
On the last step, skip(submit) submits the form without that step and runs the submit hooks. Built-in renderers pass their submit handler, so their Skip submits. skip() without a handler returns false there. Continue or Submit on a skipped step, or a changed value of one of its fields, includes it again. checkDefinition() warns about skip on a step with next: false or in a form with one step.
Trimming
Core trims leading and trailing whitespace from string values of every built-in type except password, number, scale, rating, select, radio and file.
engine.valueskeep the raw text as typed.getSubmitValues()and the submit payload hold the trimmed text.- Validation runs on the trimmed text, so
requiredfails on a whitespace-only value. show,showAny, route conditions and actiondisabledcompare trimmed values.
Auto-advance
autoAdvance: true lets a renderer advance when the user commits an answer. The built-in radio, scale and rating commit on click, Space and Enter, and scale and rating also on a digit key; arrow keys only select. Do not set it on matrix rows. Commit validates the whole current step and then moves forward. Initial values and setValue() never advance, and the last step never auto-submits. Other built-in types ignore autoAdvance. Custom fields commit through onCommit in React and the commit event in Vue.
Answer recall
A text can show an earlier answer with a {{key}} token, where key is a top-level field key. Whitespace inside the braces is allowed: {{ key }}. Inside a group item, the item's own fields are also recalled by their item key, from the same item. A token key is made of characters from the Unicode categories L (letters), M (marks) and N (numbers), plus _, - and ., so {{contact.email}} recalls the field contact.email. Other content inside {{ }} is reserved: a token with |, ?, :, (, ), [, ], ', " or whitespace inside the key, like {{name|upper}}, shows as written, and checkDefinition() warns with recall-syntax. \{{ shows {{ and starts no token. It is the only escape: a backslash before it is kept as written, so \\{{ shows \{{. There are no expressions, filters or formats in the definition. The {{ and }} delimiters are fixed: no option or setting changes them. A definition embedded in a template that also reads {{ }} must be kept out of that template's parsing; see Embedding definitions in template engines.
json
{
"formatVersion": "1.5",
"id": "signup",
"title": "Sign up",
"submit": { "label": "Send" },
"steps": [
{
"id": "about",
"title": "About you",
"fields": [
{ "key": "name", "type": "text", "label": "Name" },
{ "key": "email", "type": "email", "label": "Email", "helperText": "We write to {{name}} here" },
{
"key": "plan",
"type": "radio",
"label": "Plan",
"options": [
{ "value": "pro", "label": "Pro" },
{ "value": "team", "label": "Team" }
]
}
]
},
{
"id": "review",
"title": "Review",
"description": "Check your answers: {{name}}, {{email}}, plan {{plan}}",
"fields": [{ "key": "notes", "type": "textarea", "label": "Anything to add?" }]
}
]
}Tokens are resolved in the step title and description, the section title and description, the field and group label and helperText, the field placeholder and the group itemLabel. The itemLabel is resolved inside each item, in one pass with its {label} and {index} parameters: text that one of them inserts is never read again. Option labels, action labels, catalogs and messages show tokens as written. Recall works only with formatVersion 1.5 or newer.
A token is replaced with the answer of the field. When fields on different route branches share a key, the token reads the field on the active path, with its own options and type:
| Field | Answer |
|---|---|
select, radio, autocomplete | the option label from the definition options; a value without one, such as a value from optionsFrom, as is |
multiselect | the list of option labels |
checkbox, switch | the field label when true, else empty |
number, scale, rating | the number |
date, time, datetime, text types other than password, hidden | the value as stored |
password | empty, also when another field with the same key on another route branch, or in another group with the same key, is not a password |
file | the file name, or the list of file names of a file list. A file the renderer stored shows its name, never a path or URL. A reference the app supplied shows as written |
| group | the number of items |
A field without a value, an empty list, a field that conditions hide, a field on a step off the active path or a skipped step, and an unknown key give an empty text. After the tokens and the itemLabel parameters are replaced, a text longer than 10000 UTF-16 code units is cut to its first 10000. When the last unit kept is a high surrogate, it is dropped too, so the text never ends in half a character. The same cut applies to a message or label filled with parameters, such as an item title from the itemLabel label or its default. Swift counts the units of String.utf16. Recall runs once. Inserted text is never read again: a value, an option label or a checkbox label that holds {{key}} or \{{ shows as written. The result is plain text. Renderers MUST draw a resolved text as plain text and MUST NOT interpret it as HTML, Markdown or any other markup. Other outputs encode it for their context, as Output safety describes. React and Vue update the texts when a value, lang or formatRecall changes. recallText(definition, text, values, { item?, lang?, format?, engine? }) from @formhaus/core resolves a text with the values from engine.getSubmitValues(); item is { group, index } for a text inside a group item. With engine, a shared key reads the field on the engine's active path. Without it, the path is computed from values, which leave out skipped steps, so a route that reads a skipped step's default can pick another branch.
An optional answer can be empty, so {{street}}, {{city}} can show , Springfield. Put each optional recall on its own line or in its own text instead of joining answers with punctuation.
checkDefinition() reports each recall warning code at most once per text, for its first token.
Resolved texts are for display only. Conditions, routes, exclusive options, the submit payload, errors, form events and translation addresses identify fields by key, steps by id and options by value, never by a resolved text. Event payloads carry stepId and fieldKey, never a resolved title or label. The error summary groups errors by step id and shows the resolved step title and field label. Messages show tokens as written, so a built-in message that names a hidden field by its label keeps the label's tokens. An app that matches or tracks forms by text uses keys, step ids and option values, or recallStatic() for a text that stands for many submissions.
Recall formatting
Each answer that is not empty goes through one formatter, (value, field, locale) => string. value is a text, a number or a list of texts, as the table above gives it. Apps replace the formatter with the formatRecall option of the engine and the renderers. The locale is the lang option of the engine or renderer, then the definition lang, then en. An overlay carries no locale: the app that applies it passes lang, to the renderer or to localize().
The identity formatter writes a text as is, a number as JavaScript String() writes it (0 for -0, 1e+21, 0.30000000000000004) and a list joined with , . The conformance corpus checks recall with it. Per-submission texts outside a form, such as emails, webhooks and PDFs, resolve with the values of that submission and the identity semantics. Texts that stand for many submissions, such as CSV headers and statistics, use recallStatic(definition, text, group?): it replaces each token with the label of its field, the key for a field without a label, and an empty text for an unknown key. With group, item keys of that group are read first, as inside an item.
The default formatter uses the platform formatters, so the exact text depends on the platform and its locale data:
| Answer | @formhaus/core | Swift |
|---|---|---|
date | Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeZone: 'UTC' }) | Date.FormatStyle(date: .abbreviated, time: .omitted) in UTC |
time | Intl.DateTimeFormat(locale, { timeStyle: 'short', timeZone: 'UTC' }) | Date.FormatStyle(date: .omitted, time: .shortened) in UTC |
datetime | Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' }) | Date.FormatStyle(date: .abbreviated, time: .shortened) in UTC |
| number | Intl.NumberFormat(locale, { maximumSignificantDigits: 21 }) | .number.precision(.significantDigits(1...21)) |
| list | Intl.ListFormat(locale, { type: 'conjunction' }) | .list(type: .and, width: .standard) |
| text | as is | as is |
Numbers are formatted only for number, scale, rating and the item count of a group, and -0 shows as 0. A number that JavaScript writes with an exponent, below 1e-6 or from 1e21, and a number in any other field show as the identity formatter writes it, so no digit is lost. A date or time is formatted only when it passes the type check of its field. A stored date or time shows the day and clock as written: it is read in UTC and formatted in UTC, and an offset in a datetime is ignored, so 2027-06-14 never shows as the 13th. Runs of whitespace in a text or list item collapse to one space. A value that does not parse as its type, or an impossible date such as 2027-02-30, shows as the identity formatter writes it. A malformed locale or one the platform does not support falls back to en.
The token grammar, the slots, the answer table, the identity formatter and the formatter signature are fixed for format 1.x. The default styles are platform-native and can change in a 1.x release.
Translations keep the tokens. Recall resolves the translated text, and option labels come from the translated definition. translationIssues() reports a translation that drops or adds a {{key}} token in placeholderMismatch.
Submit payload
getSubmitValues() and the submit handler receive an object with:
- every visible field with a value other than
undefined, on every step of the active path, or every visible field of a single-step form; null,'',falseand[]values included;- fields of skipped steps, fields hidden by conditions, fields off the active path and keys that are not field keys excluded. With
hiddenValues: "keep", fields hidden by conditions and fields off the active path are included.
Keys are field keys as written. The payload is not nested and not type-converted. Section fields are top-level keys. A group value is an array of item objects: each holds the visible item fields with a value other than undefined, trimmed like top-level values, and no other keys.
With the built-in renderers, a visible field on the active path has these payload values:
| Field state | Payload |
|---|---|
| Untouched | its start value, or key absent without one |
| Text cleared by the user | "" |
number cleared by the user | null |
checkbox or switch unchecked by the user | false |
file cleared by the user | null |
file with multiple after the user removes every file | [] |
Fields hidden by conditions, on a skipped step or off the active path are absent. These are value representations, not a record of what the user did. An untouched field with an initial value of null sends null. An edit flow must not read an absent key as "keep the stored value". validateSubmission() reads an absent key as absent too: it applies no defaultValue, defaultItems or item field default to it, and it keeps no last values, so it restores nothing that the payload does not hold. It resets the fields of each step in skippedSteps like Skip does, ignores the values sent for them and evaluates conditions against the reset values. A value that fails its type check, at top level or in a group item, gets only its type error and is left out of the returned values; conditions and validators treat the field as unanswered. "" and null count as empty for required, and notEmpty does not match them.
Reopening a draft through initialValues starts without last values, so a hidden field the draft omits gets its defaultValue when it is shown.
A file value in the browser is a File, or null after clearing. A file list is an array of them. Core does not upload it, and how it reaches the server is the app's choice, such as FormData or an uploader that returns a reference. validateSubmission() on the server checks a file value as a string reference. A file value that is not a File, such as a string or a file: URL in the initial values, is a reference the app supplied. The built-in renderers do not show it, link to it or fetch it, the engine submits it as given, and the Cloud uploader sends it without an upload. The fixtures file-app-reference.json in the corpus and in scenarios/ pin this rule.
Unsaved changes
Dirty tracking is an opt-in module: @formhaus/core/dirty in TypeScript. It follows a running engine and compares its submit payload with a baseline.
- The baseline holds the values, the definition and the skipped steps when tracking starts, right after the engine is created with its initial values. The baseline payload is the submit payload at that moment.
- A key is dirty when its value in the current payload differs from its baseline value. Numbers compare with SameValueZero:
0equals-0andNaNequalsNaN. Strings and booleans compare by value, arrays by items in order, plain objects by keys in any order. A file equals only the same file: JavaScript comparesFileobjects by reference, and a port compares its file references by content. Other values compare by reference. A key missing on one side differs from any value on the other,nulland''included, andnulldiffers from''. - For a group whose items are objects on both sides and whose item count is the same, the dirty keys are the item paths
<group>.<index>.<field>whose values differ. When the item count differs, the dirty key is the group key. - Trimming, hidden fields,
hiddenValuesand skipped steps apply as in the payload. A trim-only edit is not dirty. A value that a condition hides is dirty unlesshiddenValuesis"keep". Skipping a step drops its values from the payload, so they are dirty until the step is included again. - The dirty keys are sorted by UTF-16 code units. The form is dirty when the list is not empty.
markClean()sets the baseline to the current payload. Everyreset(values)of the engine sets the baseline to the resulting payload. The engine counts resets inresetCount, which changes before the reset notifies subscribers, and the tracker takes a new baseline when the count changed.- After
replaceDefinition(), the baseline payload is recomputed: an engine created with the baseline values, definition and skipped steps is switched to the current definition, and its payload is the new baseline payload. A definition swap alone, with new fields and their defaults or removed fields, is not dirty. Edits made before or after it are. - Listeners run when the list of dirty keys changes, not in the middle of
reset.
The conformance file scenarios/dirty.json pins these rules.
Submit results
The submit handler receives the submit payload and the skipped step ids. It MAY return a result, directly or through a Promise:
ts
type SubmitResult =
| { ok: true }
| { ok: false; errors?: Record<string, string>; formErrors?: string[] }| Handler outcome | submit() resolves | Values | Errors | onAfterSubmit |
|---|---|---|---|---|
{ ok: true }, undefined or any value other than a rejection | true | Kept | Cleared | Runs once |
A rejection: a plain object with ok: false | false | Kept | Replaced by the result | Does not run |
| Throws or rejects | Rejects with the same error | Kept | Unchanged | Does not run |
A plain object is one whose prototype is Object.prototype. A fetch Response with ok: false is not a rejection, so a handler that returned it still counts as a success.
Server errors
errors keys are field keys or item paths. An item path refers to the items as they were sent; errors of a group whose value changed during the request are dropped. A message that is not a string is ignored; an array of strings is joined with spaces. formErrors other than an array of strings is ignored. A rejection and setErrors(errors) apply a server error set the same way:
- A key of a visible field on the active path, or the path of a visible item field of an existing item, becomes the error of that field. Every other key, including the key of a field hidden by its conditions or a field off the active path, becomes a form-level error. An error on a field of type
hidden, at top level or in a group item, stays under its key or path and is also listed intopLevelErrors. Form-level errors are theformErrorsmessages, then the unmatched messages in key order. They are exposed astopLevelErrors. - The set replaces all previous field errors and form-level errors at once.
- In a multi-step form, the engine opens the earliest step on the active path that has a field error. The key order of
errorsdoes not matter. The step change hooks do not run. - The built-in renderers apply the focus rule of a failed Submit on that step after it renders: the error summary for two or more errors, otherwise the first invalid field on the step: the checked option of a group, or its first enabled control.
Field errors are kept until one of these events:
| Event | Server field errors | Form-level errors |
|---|---|---|
| The field gets a different value | That field's error is removed | Kept |
| The field is hidden by conditions, its step leaves the active path, or its step is skipped | That field's error is removed | Kept |
validateField(key) finds no client error | That field's error is removed | Kept |
Navigation, Continue, validate() and onStepValidate errors | Kept | Kept |
| A new submission is sent | Kept while it runs | Kept while it runs |
A rejection or setErrors() | Replaced | Replaced |
A successful submission or reset() | Removed, unless setErrors() ran during the request | Removed, unless setErrors() ran during the request |
Writing the same value again keeps the error. While a client rule fails on a field with a server error, the client error shows; the server error returns when the client error is resolved. Server errors do not block Continue or Submit. Client rules decide whether the request is sent.
Concurrent submissions
- One action runs at a time.
submit()andskip()while a submission or navigation is pending resolve tofalsewithout calling the handler. - A response that arrives after
reset(),cancelPendingActions(), a definition change or an unmount is ignored. It applies no errors, does not navigate and does not runonAfterSubmit.submit()still resolves totruefor a success andfalsefor a rejection. - The built-in renderers disable fields while a submission runs. When the engine is driven directly and a value changes during the request, a success still runs
onAfterSubmitwith the values that were sent. A rejection skips the errors of fields whose value changed after the request was sent. - The engine does not abort a request. A handler that needs to abort uses its own
AbortController.
Form events
After start(), the engine reports these sequences through onFormEvent. ? marks an event that fires only in that case, * one that fires once per field.
| Action | Events in order |
|---|---|
| Continue that passes | step_completed for the current step, step_viewed for the next |
| Continue that fails | field_error* |
| Back | step_viewed |
goToStep | step_viewed when the step changes, then step_redirected when the target was not reached |
| Skip on a step before the last | step_skipped, step_viewed |
| Submit that fails validation | form_submit_failed with reason: 'validation', field_error* |
| Submit with a successful handler | step_skipped? for Skip on the last step, form_submitted, form_submit_succeeded |
| Submit with a rejection | form_submitted, form_submit_failed with reason: 'rejected', field_error* for the rejected fields |
| Submit with a handler that throws | form_submitted, form_submit_failed with reason: 'error' |
The last step never reports step_completed: form_submitted closes it. A funnel counts the users who left on the last step as step_viewed for it without form_submitted. onBeforeSubmit returning false reports nothing.
For reason: 'error', status is the numeric status of the thrown error when it has one. CloudError sets it: 0 without a response, such as a network failure, otherwise the HTTP status.
form_submitted fires after onBeforeSubmit and right before the handler runs. form_submit_succeeded fires before onAfterSubmit runs. New event types and new event fields are additive: a minor version can add them, so handle unknown types in a default branch.
Form snapshot (native ports)
Native renderers restore a form after the OS ends the app process. The JS core does not implement snapshots; web hosts use onValuesChange.
jsonc
{
"version": 1,
"definitionId": "contact",
"values": { "email": "ann@example.com" },
"step": "details",
"skipped": ["intro"],
"seed": "9f2c41d07a3b88e1"
}definitionId is the definition's id, or null when it has none. step is the current step id, or null for a form without steps. skipped lists the skipped step ids. seed is the option-order seed.
- The engine restores values, current step, skipped steps and seed directly. It does not walk the steps and does not validate. The fields of each skipped step get their start values, as a skip sets them.
- The engine MUST start fresh, report the warning
snapshot-mismatchand never throw whenversionis not 1, the definition has anidanddefinitionIdis missing,nullor different, the definition has noidanddefinitionIdis notnull,stepor an id inskippedis not a step of the definition, an id inskippednames a step without askipaction, or the JSON is malformed. - The renderer MUST report a new snapshot after each change of values, step or skip, coalesced, and MUST NOT report one during restore.
- After a successful submit, including a Skip on the last step that submits, the renderer MUST report a cleared snapshot (
null) so the host drops its draft. This holds when the form view went away while the submit was sending. - The host stores the snapshot. Values can hold personal data.
- A snapshot MUST NOT contain values of
passwordfields, includingpasswordfields inside group items.snapshot()leaves them out and on restore they stay empty, sorequiredcatches them again. Snapshots may be written to disk. No other values are excluded: hidden fields keep their values according tohiddenValues. - On restore, a file value inside the renderer's own upload storage is re-adopted if the file still exists and becomes
nullotherwise. In a file list, each such file is re-adopted or removed from the list. Other values are untouched. - When the form view goes away during a submit, a submit that already reached the submit handler MUST run to completion, including the after-submit callbacks.
Translations
A definition holds its texts in one language, the source language. Catalogs, translation keys and overlays change texts only. They never change fields, rules, routes or the submit payload.
Message and label catalogs
messages replaces the built-in validation messages and labels the built-in renderer texts. Values are templates: {name} is replaced by the param of that name, and unknown placeholders stay as they are. Core skips a value that is not a non-empty string. checkTranslations() reports it as invalid-type.
| Message key | Default | Params |
|---|---|---|
required | This field is required | |
minLength, maxLength | Minimum length is {min}, Maximum length is {max} | min, max |
minItems, maxItems | At least {min} required, At most {max} allowed | min, max |
min, max | Must be at least {min}, Must be at most {max} | min, max |
pattern | Invalid format | |
matchField | Fields must match | |
email | Enter a valid email | |
number | Enter a number | |
date | Enter a valid date | |
datetime | Enter a valid date and time | |
time | Enter a valid time | |
option | Select one of the available options | |
options | Must be a list of available options | |
exclusive | Select "{option}" or other options, not both | option (the label of the exclusive option) |
boolean | Must be true or false | |
string | Must be text | |
file | Must be a file reference | |
value | Invalid value | |
hidden | {label}: {message} | label, message |
minLength and maxLength on an array value, including a group, use minItems and maxItems. The 10,000-character limit of the type check uses maxLength. A multiselect value that is not an array or repeats a value fails with options, and one that holds an exclusive option with other values fails with exclusive; an item that is not a static option fails with option.
| Label key | Default | Params |
|---|---|---|
continue | Continue | |
back | Back | |
stepOf | Step {current} of {total} | current, total |
errorSummary | Check these answers | |
addItem | Add | |
removeItem | Remove | |
itemLabel | {label} {index} | label, index |
itemAdded | {item} added | item |
itemRemoved | {item} removed | item |
removeItemNamed | {label} {item} | label (the Remove text), item |
removeItemPrompt | Remove {item}? | item |
removeItemBody | This removes {item} and its answers. This cannot be undone. | item |
cancel | Cancel | |
enlargeImage | Enlarge image: {label} | label (the option label) |
close | Close | |
clear | Clear | |
done | Done | |
chooseFile | Choose file | |
required | required | |
skip | Skip | |
submit | Submit | |
stepTitle | Step {index} | index (1-based) |
stepErrors | Errors: {count} | count |
fileCount | Files: {count} | count |
moveUp, moveDown | Move up, Move down | |
itemMoved | {item} moved to position {position} | item, position |
readOnly | Read only | |
or | or | |
select | Select |
A message for a failed rule comes from the first of:
- The field message: a string
required,minLengthMessage,maxLengthMessage,minMessage,maxMessage,patternMessageormatchFieldMessage. - The
messagesoption of the engine, the renderer orvalidateSubmission(). - The translations of the
localeoption, in order. definition.messages.- The catalogs of the
localeoption, in order. - The default.
A label comes from the explicit action label, then the labels renderer option, then the translations of locale, then definition.labels, then the catalogs of locale, then the default. skip and submit apply when the step skip or the form submit has no label. stepTitle names a step without a title in the step progress, and stepErrors marks a step with errors there. or is the divider before exclusive options. select is the prompt of an empty select. clear names the button that clears a field, done the button that confirms a date or time picker, and chooseFile the button that opens the file picker. In a file list, removeItem, removeItemNamed, itemAdded and itemRemoved name the Remove button of a file and announce changes, with the file name as item. Native renderers read the number of files with fileCount; web renderers do not use it. moveUp, moveDown and itemMoved name the Move buttons of a reorderable group and announce a move. Native renderers announce readOnly as the state of a read-only field; web renderers use readonly and aria-readonly instead. required is the word assistive technology announces for a required field. The web renderers add it as visually hidden text to the legend of a required radio, multiselect, scale or rating group. Web renderers use aria-required and the browser file input, so they do not show clear, done, chooseFile or select. A messages or labels option MAY be a function (key, params, field) or (key, params). Its result is final text and is not formatted again. undefined or '' falls through to the next source.
Core resolves a message when the rule fails. Errors stay strings. The messages option is fixed for the lifetime of an engine.
Translation keys
An i18n object maps texts of its node to keys of the app dictionary, such as Lokalise keys:
| Node | Slots |
|---|---|
| definition | title, description, messages.<key>, labels.<key> |
| step, section | title, description |
| field | label, placeholder, helperText |
| group | label, helperText, itemLabel, addLabel, removeLabel |
| option | label, description |
| action | label |
| validation | required, minLength, maxLength, min, max, pattern, matchField |
The text of a bound slot MUST exist in the node; it is the fallback wherever the app dictionary is not available. A key without its text is an i18n-key-without-text error. A validation slot MAY bind a rule without a field message. FormEngine ignores i18n; localize() from @formhaus/core/i18n reads it and throws a FormDefinitionError on translation errors.
json
{
"id": "signup",
"title": "Sign up",
"submit": { "label": "Create account", "i18n": { "label": "signup.submit" } },
"fields": [
{
"key": "email", "type": "email", "label": "Email",
"i18n": { "label": "signup.email.label" },
"validation": { "required": "Enter your email", "i18n": { "required": "errors.emailRequired" } }
}
]
}Addresses
An address names a text slot by identifiers, never by array index:
text
title | description
submit.label | cancel.label
messages.<key> | labels.<key>
fields.<key>.label | placeholder | helperText
fields.<key>.options.<value>
fields.<key>.optionDescriptions.<value>
fields.<key>.validation.<rule>
steps.<id>.title | description
steps.<id>.next.label | back.label | skip.label
steps.<id>.fields.<key>.label | ...
sections.<key>.title | description
steps.<id>.sections.<key>.title | description
fields.<group>.label | helperText | itemLabel | addLabel | removeLabel
fields.<group>.fields.<key>.label | ...Fields of a multi-step form are addressed under their step, so a key shared by two exclusive route branches has one address per branch. Fields of a section keep the address they have outside it. Item fields are addressed under their group. {index} in an itemLabel is a placeholder, so a translation MUST keep it.
Overlays
An overlay is a JSON object of translated texts, nested by address. Every leaf is a string, except that a messages or labels entry MAY be an object of plural forms with a required other. A root locale string names its language. Its JSON Schema is https://formhaus.dev/schema/form-translation.json, shipped as @formhaus/core/translation.schema.json.
json
{
"locale": "ru",
"title": "Регистрация",
"submit": { "label": "Создать аккаунт" },
"messages": { "required": "Обязательное поле", "minLength": "Минимум {min} символов" },
"labels": { "stepOf": "Шаг {current} из {total}" },
"fields": {
"email": { "label": "Почта", "validation": { "required": "Укажите почту" } }
}
}localize(definition, translation(overlay)) returns a copy of the definition:
- A text is replaced only by a non-empty string. Missing, empty and non-string entries keep the source text.
- Entries without a source slot are ignored. An overlay never adds fields, options, rules or actions.
- A validation entry applies only when its rule is set. It becomes the field message, with
{min}and{max}replaced by the rule value. Field messages in the definition itself are used as written. - String
messagesandlabelsentries are merged into the definition catalogs. Plural forms apply when the text is shown. langbecomes thelocaleof the overlay.- Only own properties are read.
Translate function
localize(definition, translation({ locale, translate, prefix })) calls translate(key, params, defaultText) for each slot. The key is the explicit i18n key, or <prefix>.<address>, where prefix defaults to the form id. With prefix: false only explicit keys are asked. A result of undefined, '' or the key itself, or a thrown error, means no translation, and the source text stays. {name} placeholders left in a result are filled in like overlay templates.
Texts, options, action labels and field messages are translated once. For a rule without a field message, a result equal to defaultText is not written, so the catalog still applies. Catalog messages and labels are translated when they are shown, through the messages and labels functions that localize() returns.
localize() also takes a list of translations and catalogs, the same list as the locale option of the engine and the renderers.
lang is metadata. It does not select a translation and does not set dir.
Definition checks
checkDefinition(definition) never throws. It returns a list of issues. Each issue has a code, a severity (error or warning), a JSON pointer path to the node, a message of the form <path>: <what is wrong>. <how to fix>., and an optional hint with the fix. Errors come before warnings.
The FormEngine constructor runs the same checks. It throws a FormDefinitionError with the errors in issues, and passes each warning to the onWarning option. Without onWarning, it logs warnings with console.warn. When process.env.NODE_ENV is production, or process is not defined, the constructor runs only the error checks and reports no warnings. Each of its errors, and each error from replaceDefinition(), has the message <path>: <code> and no hint. checkDefinition(), parseDefinition() and development builds give the full message. validateSubmission() does not log warnings.
| Code | Severity | Reported for |
|---|---|---|
invalid-type | error | A definition that is not an object; fields, steps, steps[].fields, the fields of a section or a group, routes, options, show, showAny or disabled that is not an array of objects; or a property of the wrong type, such as an id that is not a string, in that is not an array, max that is not a number, a source that is not a name or a { "query" } object with a parameter name, or a formatVersion that is not a version string |
unsupported-format-version | error | A formatVersion with a major version newer than this core reads |
missing-property | error, warning | A missing id, submit, step id or fields, field key or type, option value, route to or condition field. A missing form, step or section title is a warning. The path points to the object that lacks the property |
missing-label | warning | A field other than hidden, an option or an action without label, or a field other than hidden with an empty or blank label. The path points to the label property |
unknown-property | warning | A property the JSON Schema does not define, such as imd for id. The hint names the closest known property, or the validation object for a rule set on a field |
fields-and-steps | error | Both fields and steps non-empty |
duplicate-step-id | error | Two steps with one id |
reserved-key | error | A field key that is a built-in object property name, such as constructor |
route-target | error | A route target that is not a later declared step id or null |
unknown-field | error, warning for optionsDependsOn | A condition, matchField or optionsDependsOn key that is not a field key, including a section key |
group-scope | error | A condition or matchField outside a group that uses a field inside it, or an item field that uses a field of another group |
invalid-nesting | error | A section inside a section or a group, or a group or file field inside a group, or a hidden field inside a group below format 1.9 |
forward-reference | error | A field or route condition on a later step, or a step condition on the same or a later step |
condition-operator-count | error | A condition with no operator or with several |
unknown-operator | error | A condition key that is not an operator |
condition-cycle | error | Show conditions that depend on each other in a cycle |
invalid-pattern | error | A pattern that is not a valid regular expression |
duplicate-key | error | A field or section key that an earlier one on a possible path already uses, an item key that repeats a key of the same group or a key outside it, or a key that starts with a group key and . |
duplicate-option-value | error | An option value that an earlier option of the same field already uses |
min-greater-than-max | error | minLength greater than maxLength, or min greater than max |
default-items-greater-than-max | error | A group defaultItems greater than its maxLength |
group-item-limit | warning | A group defaultItems greater than 100 without maxLength, or a group maxLength or defaultItems greater than 1000 |
invalid-columns | error | A number columns that is not a whole number from 1 to 4 |
invalid-scale | error | A scale or rating whose min or max is not an integer, or whose range has fewer than 2 or more than 11 points |
unknown-source | error | A source string that is not a source name |
source-in-group | error | A source on a hidden field inside a group |
condition-value-mismatch | warning | A condition value of the wrong type for the field, a value that is not one of its static options, or eq, neq, in or notIn on a multiselect |
contains-not-list | warning | contains or notContains on a built-in field that does not hold a list, or on a group. Only multiselect holds a list; custom types are not checked |
contains-not-in-options | warning | A contains or notContains value that is not one of the static options of the multiselect |
slow-pattern | warning | A pattern that repeats a group with a quantifier or an alternation inside, such as (a+)+, or repeats overlapping parts next to each other, such as \d*\d*, which can take very long to match. A repeated group without alternation that starts or ends with a separator that nothing else in the group matches, such as ([a-z]+\.)+, (,\s*[a-z]+)* or ([ '-][A-Za-z]+)*, is not reported. A separator is a character, an escape or a character class, with no quantifier, or with + when the group has another part that is not optional. A group with no unbounded quantifier inside, repeated a fixed number of times or at most 10 times, such as (?:[0-9a-f]{3}){1,2}, is not reported. A repeated group next to another repeated part counts as overlapping when the part can match the group's separator, or the group's first characters when it has none. A pattern longer than 1000 characters is reported without a scan |
rule-not-applicable | warning | min/max on a built-in type other than number, scale and rating or on a group, or minLength/maxLength on number, scale, rating, checkbox or switch |
condition-always-true | warning | notEmpty: false, which matches every value |
default-disabled-option | warning | A defaultValue that is a disabled option, from format 1.8 |
disabled-not-applicable | warning | disabled on a back, skip or cancel action, which the built-in renderers ignore, or on an option of a field other than radio, select and multiselect |
outdated-format-version | warning | A section or a group in a definition without formatVersion 1.1 or newer, a scale or rating field without 1.3, a contains or notContains condition without 1.4, a {{key}} token, an exclusive option or an autocomplete without 1.5, randomize or pinned without 1.6, multiple without 1.7, or an option description or disabled, a readOnly or a reorderable without 1.8 |
unknown-recall-field | warning | A {{key}} token whose key is not a top-level field key or, inside a group item, an item key |
recall-forward-reference | warning | A {{key}} token for a field on a later step, or for the field that holds the text |
recall-syntax | warning | A {{ }} token with content other than a field key. It shows as written |
recall-sensitive-field | warning | A {{key}} token for a key that is a password field on any route branch. It shows nothing |
recall-query-source | warning | A {{key}} token for a hidden field with a query source, whose text anyone can set in a link |
recall-untrusted-source | warning | A {{key}} token for a hidden field with a referrer or pageTitle source, whose text another site can set |
missing-options | warning | select, radio or multiselect without options or optionsFrom |
default-not-in-options | warning | A defaultValue that is not one of the options |
unknown-field-type | warning | A field type that looks like a typo of a built-in type, such as txt. A type with - or : is reported only when it spells a built-in type with separators, such as multi-select |
custom-type-name | warning | A custom field type without - or :, such as stars. Not reported when unknown-field-type is |
definition-reset | warning, from the React and Vue renderers in development | A new definition object with the same content as the previous one, which resets the form |
missing-component | warning, from the React and Vue renderers in development | A field type with no component in components. Reported once per type |
legacy-layout | warning, from the React and Vue renderers in development | components.section, components.group, components.groupItem, components.confirmDialog, actionsComponent or progressComponent, which layout replaces. Reported once per key |
missing-research | warning, from the engine in development | A field with randomize and no research option, so the options show in written order. Reported once |
untranslated-locale | warning, from the engine in development | A locale source with texts of the form, such as title or fields, that was not passed through translation(), so those texts stay in the source language |
source-not-applicable | warning | A source on a field that is not hidden |
unknown-autocomplete-token | warning | An autocomplete that is not a valid autofill token |
autocomplete-not-applicable | warning | autocomplete on a built-in field type other than text, email, phone, password, textarea, number, date, select, autocomplete and radio |
columns-not-applicable | warning | columns on a field whose options have no image, on a field other than radio or multiselect, or on a field whose parent has layout: "matrix" |
unsafe-image-url | warning | An option image that does not start with https: or data:image/ |
exclusive-not-applicable | warning | exclusive on an option of a field other than multiselect, or of a field with optionsFrom |
exclusive-option-position | warning | An exclusive option followed by an option that is not exclusive |
exclusive-default-value | warning | A defaultValue that holds an exclusive option and other values |
exclusive-with-min-length | warning | minLength greater than 1 on a multiselect with an exclusive option |
multiple-not-applicable | warning | multiple on a field other than file |
randomize-not-applicable | warning | randomize on a field other than radio, multiselect and select or in a section with layout: "matrix", or pinned on an option of a field without randomize |
matrix-options-mismatch | warning | A radio or multiselect row of a section with layout: "matrix" whose option values differ from those of the first field, in content or order |
snapshot-mismatch | warning | A native port restored a form from a snapshot it could not use, so the form started fresh |
snapshot-too-large | warning | A native renderer did not persist a snapshot because it exceeded the platform's size limit |
unknown-validator | warning | A validator name missing from the validators option. Reported only when validators are passed |
skip-unreachable | warning | skip on a step with next: false, or in a form with one step |
route-fallthrough | warning | A branch that falls through into a sibling branch |
i18n-key-without-text | error, from checkTranslations() | A translation key for a text the node does not have, such as i18n.placeholder without placeholder |
unknown-i18n-slot | warning, from checkTranslations() | An i18n key for a text the node cannot have, or for a rule that is not set |
unknown-message-key | warning, from checkTranslations() | A messages or i18n.messages key that is not a message key |
unknown-label-key | warning, from checkTranslations() | A labels or i18n.labels key that is not a label key |
i18n-unsafe-identifier | warning, from checkTranslations() | A form id, step id, field key or option value with . or : in a definition with translation keys |
checkTranslations(definition) from @formhaus/core/i18n checks lang, messages, labels and i18n: it reports invalid-type for a value that is not a non-empty string and the translation codes above. checkDefinition() and the FormEngine constructor do not run it.
parseDefinition(input) returns the input typed as a definition, or throws a FormDefinitionError with the errors.
Fixes
@formhaus/core/fix turns issues into repairs. The main entry does not include it.
ts
import { applyFix, fixAll, suggestFixes } from '@formhaus/core/fix';
const issues = suggestFixes(definition);
const fixed = applyFix(definition, issues[0].fixes[0].patch);
const { definition: repaired, applied, issues: left } = fixAll(definition);suggestFixes(definition, issues?) returns the issues of checkDefinition(), or the issues you pass, with fixes on the issues it can repair. Each fix is { title, safe, patch }. patch is a list of JSON Patch operations: add, replace, remove and move. A fix with safe: true repairs the issue and changes nothing else.
applyFix(definition, patch) returns a new definition and leaves the input as is. It throws when a path does not exist or the patch has an unknown operation. fixAll(definition) applies safe fixes until none are left, up to 500 rounds, and returns the definition, the applied fixes and the remaining issues.
| Code | Fix | Safe |
|---|---|---|
unknown-property | Rename to the property in the hint, such as imd to id | yes |
unknown-property on a rule set on a field | Move the rule into validation | no, the rule starts to apply |
missing-property | Rename a misspelled property when there is one. Otherwise form or step id from the title (my-form or step-2 without one), field key from the label (field without one), option value from its label, submit with the label Submit, step fields as an empty list | yes |
missing-label | Rename a misspelled property when there is one. Otherwise field and option label from the key or value, such as First name for firstName, action label from the default button text | yes, except next and back labels in a definition with labels or lang, and cancel |
duplicate-key | Rename the later key with _2, _3 | when no condition, matchField or optionsDependsOn uses the key |
duplicate-option-value | Change the later value with _2, _3 | when no condition and no defaultValue uses the value |
duplicate-step-id | Rename the later id with -2, -3 | when no route targets the id |
invalid-type on formatVersion | Set formatVersion to the current version | when the major version matches, such as 1 or "v1" |
unsupported-format-version | Set formatVersion to the current version | no |
unknown-field, route-target | Use the closest field key or step id the reference may point to | when it is the only name within one edit (insertion, deletion, substitution or swap of adjacent letters, ignoring case) and no other name is within two edits |
unknown-field-type, unknown-operator | Use the closest existing name | no |
min-greater-than-max | Swap the two bounds | no |
Other codes, such as invalid-pattern and condition-cycle, have no fix.
JSON Schema
The JSON Schema is published at https://formhaus.dev/schema/form-definition.json and ships as @formhaus/core/schema.json. A definition MAY set $schema to that URL for editor validation and completion. The schema checks shape only. Rules that depend on other parts of the definition, such as route targets, are checked by checkDefinition().
Minimal single-step definition:
json
{
"$schema": "https://formhaus.dev/schema/form-definition.json",
"id": "contact",
"title": "Contact",
"submit": { "label": "Send" },
"fields": [
{ "key": "name", "type": "text", "label": "Name", "validation": { "required": true } }
]
}Complete example
This definition is normative. It uses conditions, defaults, validation, routes with convergence, to: null, skip and action overrides.
json
{
"$schema": "https://formhaus.dev/schema/form-definition.json",
"id": "account-application",
"title": "Open an account",
"submit": { "label": "Open account" },
"cancel": { "label": "Cancel", "variant": "text" },
"steps": [
{
"id": "kind",
"title": "Account type",
"next": false,
"back": false,
"fields": [
{
"key": "accountType",
"type": "radio",
"label": "Account type",
"autoAdvance": true,
"validation": { "required": "Choose an account type" },
"options": [
{ "value": "business", "label": "Business" },
{ "value": "personal", "label": "Personal" },
{ "value": "waitlist", "label": "Not sure yet" }
]
}
],
"routes": [
{ "to": null, "show": [{ "field": "accountType", "eq": "waitlist" }] },
{ "to": "business", "show": [{ "field": "accountType", "eq": "business" }] },
{ "to": "personal" }
]
},
{
"id": "business",
"title": "Company",
"fields": [
{ "key": "company", "type": "text", "label": "Company name", "validation": { "required": true, "minLength": 2 } },
{
"key": "employees",
"type": "number",
"label": "Employees",
"validation": { "min": 1, "max": 10000, "maxMessage": "Contact sales for more than 10000 employees" }
}
],
"routes": [{ "to": "contact" }]
},
{
"id": "personal",
"title": "About you",
"fields": [
{ "key": "name", "type": "text", "label": "Full name", "validation": { "required": true } },
{ "key": "birthDate", "type": "date", "label": "Date of birth" }
],
"routes": [{ "to": "contact" }]
},
{
"id": "contact",
"title": "Contact",
"back": { "label": "Edit details" },
"fields": [
{ "key": "channel", "type": "select", "label": "Preferred channel", "defaultValue": "email", "options": [
{ "value": "email", "label": "Email" },
{ "value": "phone", "label": "Phone" }
] },
{
"key": "email",
"type": "email",
"label": "Email",
"validation": { "required": true, "pattern": "^[^@\\s]+@[^@\\s]+$", "patternMessage": "Enter a valid email" }
},
{
"key": "confirmEmail",
"type": "email",
"label": "Confirm email",
"validation": { "required": true, "matchField": "email", "matchFieldMessage": "Emails must match" }
},
{
"key": "phone",
"type": "phone",
"label": "Phone",
"inputMode": "tel",
"show": [{ "field": "channel", "eq": "phone" }],
"validation": { "required": true }
},
{ "key": "terms", "type": "checkbox", "label": "I accept the terms", "validation": { "required": "Accept the terms to continue" } }
]
},
{
"id": "newsletter",
"title": "Newsletter",
"skip": { "label": "Not now" },
"fields": [
{ "key": "subscribe", "type": "switch", "label": "Send me product news", "defaultValue": false },
{
"key": "topics",
"type": "multiselect",
"label": "Topics",
"showAny": [{ "field": "subscribe", "eq": true }],
"validation": { "required": "Pick at least one topic" },
"options": [
{ "value": "product", "label": "Product updates" },
{ "value": "events", "label": "Events" }
]
}
]
}
]
}With accountType: "personal", the active path is kind, personal, contact, newsletter. Values entered earlier on business stay in engine.values and are not submitted. With accountType: "waitlist", the first route ends the path at kind, and Submit appears there. Skipping newsletter submits without subscribe and topics.