Field Types
Each field type maps to a UI component. Default adapters use native HTML elements. Override any field type with your own component via the components prop.
Text fields
Types text, email, phone, number, password all render a text input. The type controls the HTML input type and keyboard on mobile.
{
"key": "email",
"type": "email",
"label": "Email address",
"placeholder": "you@example.com",
"validation": {
"required": true,
"pattern": "^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$",
"patternMessage": "Enter a valid email"
}
}number renders <input type="number"> and stores a number, or null when the user clears the input.
The email type checks the format in the browser and in validateSubmission() from @formhaus/core/server. A pattern as above adds a stricter rule.
inputMode controls the mobile keyboard without changing the field type:
{
"key": "zipCode",
"type": "text",
"label": "Zip code",
"inputMode": "numeric",
"validation": { "pattern": "^[0-9]{5}$" }
}mask provides a pattern hint. The default TextField uses it as a placeholder when no placeholder is set. Custom components receive field.mask and can implement full input masking:
{
"key": "phone",
"type": "phone",
"label": "Phone number",
"mask": "(###) ###-####"
}Autofill and line breaks
autocomplete takes an HTML autofill token, so browsers and password managers can fill personal data (WCAG 2.2, 1.3.5). Set "formatVersion": "1.5". Requires @formhaus/core 0.21. There is no default: the renderers set the attribute only when you do.
{ "key": "firstName", "type": "text", "label": "First name", "autocomplete": "given-name" }It works on text, email, phone, password, textarea, number, date, select, autocomplete and radio fields, such as country on a select. In a group item the renderers prefix section-<group key>-<index>, so each item is filled on its own. The autocomplete field type sets off when the field has no autocomplete. checkDefinition() reports an unknown token as unknown-autocomplete-token and another field type as autocomplete-not-applicable.
Sign-in and sign-up forms
Set username on the sign-in identifier and current-password on the password:
[
{ "key": "email", "type": "email", "label": "Email", "autocomplete": "username", "validation": { "required": true } },
{ "key": "password", "type": "password", "label": "Password", "autocomplete": "current-password", "validation": { "required": true } }
]On sign-up, use new-password on the password and on the repeat field, and check the repeat with matchField:
[
{ "key": "email", "type": "email", "label": "Email", "autocomplete": "username", "validation": { "required": true } },
{ "key": "password", "type": "password", "label": "Password", "autocomplete": "new-password", "validation": { "required": true, "minLength": 12 } },
{
"key": "confirmPassword",
"type": "password",
"label": "Repeat password",
"autocomplete": "new-password",
"validation": { "required": true, "matchField": "password", "matchFieldMessage": "Passwords must match" }
}
]The renderers set name to the field key, an id, a <label> linked to the input and the autocomplete attribute, so password managers can fill the form and offer to save the password.
For a two-step sign-in, put the identifier on step 1 and the password on step 2. Keep autocomplete: "username" on the identifier. Browsers and password managers handle this best when the form submits at the end. We have not tested it with every password manager.
Formhaus Cloud does not accept password fields. Use your own backend or sign-in provider for passwords.
A \n in a step or section description or in helperText starts a new line. The text stays plain; HTML and Markdown are not rendered.
Select
Dropdown with predefined options. Define options inline or load them dynamically.
{
"key": "country",
"type": "select",
"label": "Country",
"placeholder": "Select a country",
"options": [
{ "value": "US", "label": "United States" },
{ "value": "DE", "label": "Germany" },
{ "value": "JP", "label": "Japan" }
],
"validation": { "required": true }
}For dynamic options (e.g. loading data from an API), use optionsFrom:
{
"key": "category",
"type": "select",
"label": "Category",
"optionsFrom": "categories",
"optionsDependsOn": ["type"]
}Then pass the provider to the renderer:
<template>
<FormRenderer
:definition="definition"
:options-providers="{ categories: loadCategories }"
@submit="onSubmit"
/>
</template><FormRenderer
definition={definition}
optionsProviders={{ categories: loadCategories }}
onSubmit={handleSubmit}
/>The provider receives all current values and can return options directly or through a Promise:
import type { OptionsProvider } from '@formhaus/react'; // or @formhaus/vue
const loadCategories: OptionsProvider = async (values) => {
const response = await fetch(`/api/categories?type=${values.type ?? ''}`);
return response.json();
};The renderer calls the provider when the field appears and whenever a field listed in optionsDependsOn changes. If requests overlap, only the latest result is used. A rejected request leaves the previous options in place and retries after the next dependency change.
Autocomplete
Type-to-filter dropdown for long option lists. Default renderer uses <input type="text"> with a <datalist> — native browser filtering, SSR-safe. Same options shape as select (and optionsFrom works the same way). For richer pickers (MUI Autocomplete, Headless UI Combobox) plug in your own component via components.
{
"key": "country",
"type": "autocomplete",
"label": "Country",
"placeholder": "Type to filter…",
"options": [
{ "value": "US", "label": "United States" },
{ "value": "DE", "label": "Germany" }
]
}The field stores the option value. The input shows the matching label, also when the value comes from initialValues or setValue() before optionsFrom resolves. A value that matches no option is shown as is.
The suggestions list and filter by label. Typing or picking a label stores its value. Other text is stored as typed.
Native <datalist> quirks
The default renderer uses the browser's <datalist> element. The input does not enforce that the value is in the list: users can type anything. If you need "must be one of the options", add a custom validator or use a custom component (MUI Autocomplete, Headless UI Combobox).
Multiselect
Pick multiple from a list. Renders as a checkbox group. The value is an array of selected option values.
{
"key": "interests",
"type": "multiselect",
"label": "Interests",
"options": [
{ "value": "tech", "label": "Technology" },
{ "value": "design", "label": "Design" },
{ "value": "music", "label": "Music" }
],
"validation": { "required": true, "minLength": 1, "maxLength": 3 }
}minLength / maxLength on multiselect controls how many options can be selected. A value that repeats an option fails validation, so minLength: 3 needs three different options.
Options stack vertically. Set "layout": "inline" to place short options side by side, as with radio. layout was added in 0.10.0.
None of these
Mark an option "exclusive": true to make it the only answer. Picking it clears the other answers, and picking another option clears it. The renderers show "or" before it, from the or label. Requires "formatVersion": "1.5" and @formhaus/core 0.21.
{
"key": "conditions",
"type": "multiselect",
"label": "Do you have any of these conditions?",
"options": [
{ "value": "asthma", "label": "Asthma" },
{ "value": "diabetes", "label": "Diabetes" },
{ "value": "heart", "label": "Heart disease" },
{ "value": "none", "label": "None of these", "exclusive": true }
],
"validation": { "required": true }
}["none"] answers a required field. validateSubmission() rejects ["none", "asthma"]. Put exclusive options last. Several are allowed, such as "None of these" and "Prefer not to say", and they clear each other. contains and notContains test them like any option.
Checkbox
Boolean toggle with a label.
{
"key": "termsAccepted",
"type": "checkbox",
"label": "I accept the Terms of Service",
"validation": { "required": "You must accept the terms" }
}required rejects an unchecked box, so the user must check it to continue.
Radio
Pick one from a list. Options stack vertically, one full-width row per option.
{
"key": "accountType",
"type": "radio",
"label": "Account type",
"options": [
{ "value": "personal", "label": "Personal" },
{ "value": "business", "label": "Business" }
],
"validation": { "required": true }
}For a few short options, such as 1 year or 2 years, set "layout": "inline". Options then sit side by side and wrap on narrow screens. Keep the default stack for options longer than a few words. layout was added in 0.10.0.
Option descriptions and disabled options
description adds a short line under an option label. disabled turns an option off, always with true or while its conditions match. Works on radio, select and multiselect; select shows no description.
{
"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 }
]
}A disabled option cannot be picked, and validation rejects it with the option message. A defaultValue and a stored answer that already holds it stay valid: in the browser that is the initial value, on the server pass previousValues. Requires "formatVersion": "1.8" and @formhaus/core 1.9. See the specification.
Scale
Pick one number on a range, such as 1 to 5. Renders as a row of numbered boxes. The value is the number. Requires @formhaus/core 0.19 and "formatVersion": "1.3".
{
"key": "ease",
"type": "scale",
"label": "How easy was the setup?",
"validation": { "required": true, "min": 1, "max": 5 },
"options": [
{ "value": "1", "label": "Very hard" },
{ "value": "5", "label": "Very easy" }
]
}validation.minandvalidation.maxset the range. They default to 1 and 5. Usemin0 or 1 and 3 to 11 points. Bounds that are not whole numbers, or fewer than 2 or more than 11 points, are aninvalid-scaleerror.- A value outside the range or not a whole number fails with
Select one of the available options. optionsare optional anchor labels.valueis the point number as a string. The label of the first point sits under the start of the row, the last point under the end and the middle point,floor((min + max) / 2), in the center. Labels on other points are not shown.- Digit keys select a point. Arrow keys move between points. With
autoAdvance, a click, Space, Enter or a digit key moves to the next step.
NPS
An NPS question is a scale from 0 to 10. 0 counts as an answer for required.
{
"key": "nps",
"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" }
]
}Show a follow-up for detractors with { "field": "nps", "lte": 6 } and for promoters with { "field": "nps", "gte": 9 }. See Conditions.
Rating
Pick a number of stars. The value is the number of stars. Requires @formhaus/core 0.19 and "formatVersion": "1.3".
{
"key": "stars",
"type": "rating",
"label": "Rate your stay",
"validation": { "required": true, "max": 5, "min": 2, "minMessage": "Pick at least 2 stars" }
}validation.maxsets the number of stars, 5 by default. Use 3 to 10. Amaxoutside 2 to 11 is aninvalid-scaleerror.validation.minis an ordinary rule: a rating below it fails with theminmessage.optionswork as anchor labels, as on a scale.- Keyboard and
autoAdvancework as on a scale. Screen readers announce the star number.
Picture choice
Add image to the options of a radio or multiselect field. The options become a grid of cards with the picture above the label. Requires @formhaus/core 0.19.
{
"key": "room",
"type": "radio",
"label": "Which room did you book?",
"columns": 2,
"options": [
{ "value": "garden", "label": "Garden suite", "image": "https://example.com/garden.jpg" },
{ "value": "sea", "label": "Sea view", "image": "https://example.com/sea.jpg" }
]
}- The value is the option
value, as without images. - The label stays visible and names the option for screen readers, so the image has an empty
alt. - Images load lazily from the URL as given. Allow their host in
img-srcif the page has a Content Security Policy. - The image host sees the respondent's IP address. The built-in renderers send no
Refererheader.checkDefinition()warns about animagethat is not anhttps:ordata:image/URL withunsafe-image-url. selectandautocompleteignoreimage.columnssets the cards per row, from 1 to 4. Without it, cards are about 200px wide and fill the row. Phones show at most 2 per row.- The button in the corner of each image opens it at full size. Esc, a click outside or the close button closes it.
Random option order
Set "randomize": true on a radio, multiselect or select field to show each respondent the options in their own order, and "pinned": true on an option to keep it in place. The order needs the opt-in research module. Requires "formatVersion": "1.6" and @formhaus/core 1.1.
{
"key": "plan",
"type": "radio",
"label": "Which plan fits you best?",
"randomize": true,
"options": [
{ "value": "free", "label": "Free" },
{ "value": "pro", "label": "Pro" },
{ "value": "team", "label": "Team" },
{ "value": "unsure", "label": "Not sure yet", "pinned": true }
]
}Switch
Boolean toggle, styled as a switch. Same behavior as checkbox but different UI.
{
"key": "darkMode",
"type": "switch",
"label": "Dark mode"
}Textarea
Multi-line text input. Set rows to control the height.
{
"key": "description",
"type": "textarea",
"label": "Description",
"helperText": "Provide additional details",
"rows": 4,
"validation": { "required": true, "minLength": 20 }
}Date
Date picker. Uses native <input type="date"> for now. Emits YYYY-MM-DD.
{
"key": "birthDate",
"type": "date",
"label": "Date of birth"
}Datetime
Date and time picker. Uses native <input type="datetime-local">. Emits YYYY-MM-DDTHH:mm (browser default; no timezone). For richer pickers (calendar UI, timezone-aware ISO output) plug in your own component via components.
{
"key": "expiresAt",
"type": "datetime",
"label": "Expires at"
}Timezone gotcha
<input type="datetime-local"> emits YYYY-MM-DDTHH:mm with no timezone. Most APIs expect ISO 8601 with a timezone offset (2026-05-10T14:30:00Z or …+02:00). If you POST the raw value to a backend that assumes UTC, you'll silently store the wrong instant for any user not in UTC.
Two ways to fix on submit:
function toISO(local: string): string {
return new Date(local).toISOString();
}
<FormRenderer
definition={definition}
onSubmit={(values) => api.post({ ...values, expiresAt: toISO(values.expiresAt as string) })}
/>Or plug in a custom component (MUI DateTimePicker, react-aria DateField) that emits ISO directly.
Time
Time picker. Uses native <input type="time">. Emits HH:mm in 24-hour time, or HH:mm:ss when the browser shows seconds.
{
"key": "startsAt",
"type": "time",
"label": "Start time"
}The browser and validateSubmission() accept 00:00 to 23:59:59 and reject anything else, such as 24:00, 9:30 or 9:30 PM, with the time message.
File
File upload. Uses native file input. Set accept to restrict file types. The value is one File, or null. With Formhaus Cloud, FormhausForm uploads the file and submits its id.
{
"key": "document",
"type": "file",
"label": "Upload document",
"accept": "image/*,.pdf"
}Several files
Set "multiple": true to collect a list of files in one field. The value is an array of File. Picking files adds them to the list, and each file has a Remove button. The picker stops at maxLength and says so when files are dropped. required needs at least one file, and validation.minLength and maxLength count files. Without maxLength a list holds up to 100 files. With Formhaus Cloud, FormhausForm uploads each file and submits the list of ids. Requires "formatVersion": "1.7" and @formhaus/core 1.7; below 1.7 the field keeps one file.
{
"key": "receipts",
"type": "file",
"label": "Receipts",
"accept": "image/*,.pdf",
"multiple": true,
"validation": { "required": true, "maxLength": 5 }
}On your server, validateSubmission() expects an array of upload references, such as ["up_1", "up_2"]. It also accepts one reference as a list of one, so older clients that send one file keep working. Upgrade the server before the clients: @formhaus/core 1.6 and older reject a list.
Core marks the field object of a file list with an own Symbol.for('formhaus.fileList') property when it loads the definition, and so do checkDefinition() and translationTemplate() on the field objects you pass them. JSON output does not include it, but deep-equality checks that compare symbol keys, such as Jest and Vitest toEqual, see it on those field objects.
Hidden
A value sent with the answers that the user never sees. It renders <input type="hidden">: no label, no helper text, nothing to focus. The value comes from the initial values, a source or defaultValue.
{
"key": "source",
"type": "hidden",
"label": "Signup source",
"defaultValue": "website"
}label is optional. Editors and error messages use it, and fall back to the key without one.
A hidden field in a group item keeps a value per item, such as a stored id. See Hidden item fields.
Value sources
source fills a hidden field from where the respondent came from. The React and Vue renderers read it in the browser after mount.
{
"key": "utm_source",
"type": "hidden",
"label": "UTM source",
"source": { "query": "utm_source" }
}source | Value |
|---|---|
{ "query": "name" } | The URL parameter name, such as utm_campaign, ref, gclid or fbclid |
"referrer" | document.referrer without the query string and hash. Browsers usually send only the origin of another site |
"page" | The page URL without the query string and hash, such as https://example.com/pricing |
"pageTitle" | document.title |
"language" | navigator.language, such as de-DE |
"timezone" | The time zone name, such as Europe/Berlin |
"device" | mobile, tablet or desktop, from the pointer type and the viewport size |
"country" | A two-letter ISO country code. Formhaus Cloud fills it at submission. On your own server, write it into the values before validateSubmission(). In the browser it yields nothing |
For a fixed value, such as "campaign": "black-friday", use defaultValue without source.
The value of a hidden field comes from, in order:
- The initial values your app passes, including a restored draft.
""andnullcount as missing. - Its
source. - Its
defaultValue. - Nothing: the key is left out of the submit values. It is never sent as
"","undefined"or"null".
A source yields nothing when the parameter is missing or empty, there is no referrer, or the browser blocks the API. Values are trimmed, cut to validation.maxLength or else 2000 characters, and an empty string counts as nothing. A source that fails does not affect the other fields or the form. Filling a value does not call onFieldChange. The server render and the first client render use defaultValue, so hydration matches.
Inside an iframe, query and page read the URL of the iframe, and referrer is usually the embedding page.
Anyone can edit the URL, so treat these values as untrusted input. Do not mark tracking fields as required or give them pattern or minLength rules: when a visitor arrives without the parameter, or with an edited one, the rule blocks the form with an error the visitor cannot fix.
Sources never include the user agent string, screen size or other values that identify a device. To collect something else, pass it in initial values.
Without the built-in renderers, resolveSources() returns the values to pass as initial values:
import { FormEngine, resolveSources } from '@formhaus/core';
const sourced = resolveSources(definition, {
search: location.search,
href: location.href,
referrer: document.referrer,
});
const engine = new FormEngine(definition, { ...sourced, ...initialValues });Context keys are search, href, referrer, pageTitle, language, timezone, device and country. A missing key yields nothing.
A hidden field follows the same rules as any other field:
showandshowAnyapply. While its conditions fail, the value is cleared and left out of the submit values. When the conditions match again, the field gets its initial value ordefaultValueback, even after an edit. Other field types get back their last value.validationrules run, andvalidateSubmission()checks the value as text of up tomaxLength, or 2000 characters without it. A number or a list fails with thestringmessage.- An error on a hidden field shows as a form-level error, in
engine.topLevelErrors, because the user has nothing to fix. It never appears in the error summary, in step error marks or as a focus target.engine.errorsandengine.validate()still list it under its key. - Built-in messages name the field, such as
Signup source: This field is required. Thehiddenmessage template,{label}: {message}, controls the format and is translated like other messages. The key stands in for an empty label. Messages you write, such as a stringrequiredorpatternMessage, stay as written.
Server errors returned for a hidden field's key also show as form-level errors, as sent. validateSubmission() already names the field in them.
Answer recall
{{key}} in a text shows the answer to an earlier field. Set "formatVersion": "1.5". Requires @formhaus/core 0.21.
{
"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" },
{
"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": []
}
]
}A step can greet the user by the name asked on the first step:
{ "id": "more", "title": "Hello, {{name}}!", "description": "A few more questions.", "fields": [] }- Tokens work in step and section
titleanddescription, field and grouplabelandhelperText,placeholder, and groupitemLabel, which reads the fields of its own item:"itemLabel": "Guest {{guest}}". - Options show their label from the definition
options, and a value fromoptionsFromshows as stored. A checkbox or switch shows its label when on, and a group shows its item count. - Dates, times, numbers and lists are formatted for the locale:
2027-06-14shows asJun 14, 2027inen-USand a multiselect asAlpha, Beta, and Gamma. The locale is the rendererlangprop, then the definitionlang, thenen. - A missing value, a hidden field and an unknown key give an empty text. Put each optional recall on its own line, so an empty one leaves no stray comma.
- Only a key goes inside the braces. Keys may hold dots, so
{{contact.email}}works.{{name|upper}}shows as written, and\{{shows literal braces. checkDefinition()warns when a token names no field, a field answered later, or holds more than a key.- A
passwordfield shows nothing, andcheckDefinition()warns about it. - A hidden field with a
querysource holds whatever text a link puts in the URL, socheckDefinition()warns withrecall-query-sourcewhen a text recalls it. AreferrerorpageTitlesource holds text another site can set, and givesrecall-untrusted-source. Recall these fields only where any text is safe to show. - Inside a group item,
{{key}}also reads the item's own fields. - Recall runs once. An answer that holds
{{key}}shows as typed and is never expanded. - Resolved texts are for display. Conditions, the payload, errors and form events use field keys, step ids and option values, never the resolved text.
- The Derived values recipe fills a
hiddenfield from app code and recalls it.
formatRecall replaces the formatting. It gets the answer, the field and the locale, and returns the text:
<FormRenderer
definition={definition}
onSubmit={onSubmit}
formatRecall={(value, field, locale) =>
field.key === 'budget' ? new Intl.NumberFormat(locale, { style: 'currency', currency: 'EUR' }).format(Number(value)) : String(value)
}
/>The answer is a text, a number or a list of option labels or file names. The error summary uses the same formatter.
Output safety
Recalled answers are user input. Renderers draw them as plain text, never as HTML or Markdown. Encode them for the output context wherever else you use them: recallText(), recallStatic(), validateSubmission() output and texts your app builds.
| Output | Rule |
|---|---|
| HTML and email bodies | Escape HTML. Never insert as raw HTML |
| Email subjects and headers | Strip CR and LF |
| CSV and spreadsheets | Prefix a cell that starts with =, +, -, @ or a tab with a single quote |
| Slack and Telegram messages | Escape the markup characters of the platform |
| URLs | Encode and validate before building a URL from recalled text |
| AI agents and prompts | Treat as untrusted data, never as instructions |
| Any store or send | Bound the length first |
import { recallText } from '@formhaus/core';
const escapeHtml = (text: string): string =>
text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
const html = `<p>${escapeHtml(recallText(definition, 'Thanks, {{name}}!', values))}</p>`;Embedding definitions in template engines
Vue, Angular, Handlebars, Jinja and Liquid also read {{ }}. A definition inlined in their templates gets its tokens rendered by the template engine before Formhaus sees them. The delimiters are fixed, so keep the definition out of the template:
- Load the JSON from a file, an import or an API, and pass it as a prop.
- In Vue, bind it from
<script>with:definition="definition", or wrap inlined markup inv-pre. - In Angular, bind it from the component class, or wrap inlined markup in
ngNonBindable. - In Jinja and Liquid, wrap the inlined JSON in
{% raw %}and{% endraw %}. - In Handlebars, wrap it in
{{{{raw}}}}and{{{{/raw}}}}with arawblock helper that returns its content.
\{{ is the Formhaus escape for literal braces in a form text. It does not hide a token from a template engine, and Handlebars reads \{{ as its own escape.
Keys and element ids
Submitted values use each field's key exactly as written. A key such as contact.email stays one flat key and is never split into nested objects. Errors from validateSubmission() and the errors prop use the same keys.
Each field control gets the element id <form id>-<key>, and its error message gets the same id plus -error. The form id is generated per renderer, so match the end of the id, such as [id$="-email"]. In the key part, each character other than A-Z, a-z, 0-9, _ and - becomes -, so contact.email gets <form id>-contact-email. A field whose id would equal an id the renderer generates for another field, such as the helper text id of plan for a field keyed plan-helper, gets a short stable suffix instead, such as <form id>-plan-helper-1x2y3z. When the other field is a group, the group id gets the suffix.
When two keys in one form escape to the same id, such as contact.email and contact-email, the key that needs no escaping keeps the plain id. If both need escaping, the key that sorts first keeps it. The other key gets - and a short hash of the key added, such as <form id>-contact-email-1k2j3h4. The hash depends only on the key, so reordering fields does not change ids.
Custom field types
FieldType accepts any string, not just the built-in types. Name custom types with - or :, such as x-rating or acme:rating. Built-in types are single words, and names with - or : never become built-in types. checkDefinition() warns about a custom type without them with custom-type-name.
Use the components prop to provide a renderer for your custom type:
<template>
<FormRenderer
:definition="definition"
:components="{ 'color-picker': ColorPicker }"
@submit="onSubmit"
/>
</template><FormRenderer
definition={definition}
components={{ 'color-picker': ColorPickerField }}
onSubmit={handleSubmit}
/>In the definition:
{
"key": "brandColor",
"type": "color-picker",
"label": "Brand color"
}If no component is registered for a type, the form shows an "Unsupported field type" placeholder. In development the placeholder names the type, and the renderer warns once per type with the code missing-component and lists the registered types. The warning goes to onWarning when you pass it, or else to the console.
Put the settings of a custom type in props. Core ignores them, and the component reads them from field.props:
{
"key": "brandColor",
"type": "color-picker",
"label": "Brand color",
"props": { "swatches": ["#111111", "#f5f5f5"], "allowAlpha": false }
}Validate a custom type
validation.validator names one validator. To add a rule for one field on top of the check of its type, write a validator that runs the type check first:
import type { ValidatorFn } from '@formhaus/core';
const checkAddress = (value: unknown): string | null =>
typeof value === 'string' && value.split(',').length >= 2 ? null : 'Enter a street and a city';
const validators: Record<string, ValidatorFn> = {
address: checkAddress,
usAddress: (value) => checkAddress(value) ?? (/\b\d{5}$/.test(value as string) ? null : 'Enter a 5-digit ZIP code'),
};{ "key": "shipping", "type": "x-address", "label": "Shipping address", "validation": { "required": true, "validator": "usAddress" } }The value of a custom type is a string, a number or a boolean. validateSubmission() rejects an object or an array with the value message, so a component with several inputs writes one string, such as "1 Main St, Springfield, 12345".
required treats only null, "" and [] as empty, and validators never run on an empty value. Write null or "" from the component when the user clears every part.
Override default components
Override any built-in field type by passing a components prop:
<template>
<FormRenderer
:definition="definition"
:components="{ phone: CustomPhoneInput }"
@submit="onSubmit"
/>
</template><FormRenderer
definition={definition}
components={{ phone: CustomPhoneInput }}
onSubmit={handleSubmit}
/>Each custom component gets the field descriptor, the current value, and validation state:
| Prop | Type | Description |
|---|---|---|
field | FormField | Field descriptor (key, label, options, etc.) |
value | unknown | Current value |
error | string? | Validation error, if any |
loading | boolean? | Field loading state set through FormEngine.setFieldLoading() |
disabled | boolean? | Form is disabled |
testId | string? | Test id of the field when the renderer has testIds. Put it on the control as data-testid |
optionTestId | ((value: string) => string | undefined)? | Test id of one option of a choice field, with testIds on |
See Custom Fields for the full contract and the value each type expects. Put the id prop on the control, so the label and error messages stay linked. In React, call onChange(value) and onBlur(). In Vue, read modelValue and emit update:modelValue and blur, so v-model works on the component.
Explicit field activation
For a deliberate activation that may advance a step, React fields call the optional onCommit(value) callback; Vue fields emit commit with the value. This saves the value and, when field.autoAdvance is true, validates and advances a non-final step. Emit only the commit event for an activation, because it also updates the value. Ordinary edits use onChange/update:modelValue and never navigate.
The built-in radio activates on click, Space or Enter; arrows only change the selection. A custom radio should preserve that distinction and allow the selected option to be activated again after a cancelled guard. Respect disabled while hooks or submission are pending. See the complete radio example.
React example
import type { FieldComponentProps } from '@formhaus/react'
export function CustomPhoneInput({ field, value, error, disabled, onChange, onBlur }: FieldComponentProps) {
return (
<div>
<label>{field.label}</label>
<input
type="tel"
value={(value as string) ?? ''}
placeholder={field.placeholder}
disabled={disabled}
onChange={(e) => onChange(e.target.value)}
onBlur={onBlur}
/>
{field.helperText && <span>{field.helperText}</span>}
{error && <span className="error">{error}</span>}
</div>
)
}Vue example
<script setup lang="ts">
import { fieldComponentEmits, fieldComponentProps } from '@formhaus/vue'
const props = defineProps(fieldComponentProps)
const emit = defineEmits(fieldComponentEmits)
</script>
<template>
<div>
<label>{{ props.field.label }}</label>
<input
type="tel"
:value="(props.modelValue as string) ?? ''"
:placeholder="props.field.placeholder"
:disabled="props.disabled"
@input="emit('update:modelValue', ($event.target as HTMLInputElement).value)"
@blur="emit('blur')"
/>
<span v-if="props.field.helperText">{{ props.field.helperText }}</span>
<span v-if="props.error" class="error">{{ props.error }}</span>
</div>
</template>fieldComponentProps and fieldComponentEmits are runtime declarations with full types, so the SFC compiler does not need to resolve a type from the package. defineProps<FieldComponentProps>() fails in some setups because the compiler cannot follow the types of @formhaus/vue and @formhaus/core. See Runtime props in Vue.
field has everything from the definition: key, type, label, placeholder, helperText, options, validation. Full type in the Definition Reference.
Read-only fields
readOnly shows a value the user cannot change. Set true, or conditions that must all match.
{ "key": "accountId", "type": "text", "label": "Account ID", "readOnly": true }The value is submitted and validated like any other field. The control stays focusable and copyable, with readonly or aria-readonly. Pass readOnly to FormRenderer to show the whole form read-only. Requires "formatVersion": "1.8". A client can still send any value, so write fixed values on the server. See the specification.
<FormRenderer definition={definition} initialValues={settings} readOnly onSubmit={save} />Default values
defaultValue fills the field when the initial values have no entry for its key:
{ "key": "country", "type": "text", "label": "Country", "defaultValue": "DE" }Skip resets the fields of a step to their defaults.
Nested keys
Field keys are flat strings. key: "name" maps to values.name in the submit output. If you use a dot in the key (key: "address.city"), it stays flat — the submitted value is { "address.city": "Berlin" }, not { address: { city: "Berlin" } }.
This is intentional. Most forms don't need nested data, and flat keys keep the engine simple. If your backend expects nested objects, reshape the values in your onSubmit handler.
For arrays of items, use a repeatable group. Its item fields use paths such as participants.1.email.
Next steps
- Validation: add rules to your fields
- Conditional Fields: show/hide fields based on values
- Custom Actions & Progress: replace the built-in buttons and step progress
- Figma Plugin: use these field types in Figma mockups