Forms & Validation
Schema-First Forms with Formisch
Schema-first forms with Preact, Formisch, Valibot and Kamod UI. Keep schema rules, field state and visual feedback connected. Start with one complete form, then compare native inputs, composite controls and dynamic field arrays using the same validation model. Import it from @formisch/preact + valibot.
Source · API reference · Theming · Styles
Interactive preview
Preact example Local preview theme · Responsive styles follow the preview widthFull widthInstallation
Add Formisch and Valibot to the docs app. Kamod UI components stay responsible for layout and interaction, while Formisch owns the schema-backed form state.
pnpm add @formisch/preact valibotCopy an example with @kamod-ch/ui or the matching @kamod-ch/ui/… subpath. The code block switches between those two installs. Connect The Global Theme CSS and Tailwind Source Detection before your first render.
Run the command in Your Application Package. It adds the form and schema libraries to an existing Preact/Kamod setup. In this repository, the equivalent workspace command is pnpm --filter @kamod-ch/ui-docs add @formisch/preact valibot. Keep your existing dependencies and connect the Global Stylesheet once.
Usage
Create a Valibot object schema, pass it to useForm, wrap controls in FormischForm, and use FormischField render props to connect Kamod UI controls.
Follow the Complete Bug-Report Example before extracting a field. Import Field as FormischField and Form as FormischForm from@formisch/preact; keep Kamod’s Field for the visible wrapper. These Components Have Different Jobs, even though their names overlap.
The previews keep submitted data in memory for inspection. They do not persist it or call a backend. Use their Code panels as focused integration examples; their visual wrappers can differ from the full demos, whose source is linked in the header.
Form Examples & Patterns
Explore Formisch in Different Contexts, from the starting pattern to the compositions below. Begin with Demo, then compare the examples that match your content, state and layout. These are working patterns to adapt, not a list of interchangeable variant values: check the API Reference before using a prop or combining behaviors. Pay particular attention to validation feedback, field relationships and what happens after submission.
Read the Result and Its Implementation Together. Use each showcase’s Code view to inspect imports and composition, or its Prompt view to prepare a setup or adaptation brief. Try the narrow preview and local theme controls before connecting real data, and use Reset to return an example to its initial state. Keep layout changes in class utilities where appropriate; follow the Component Styles Guide for hierarchy and the Theming Guide for shared surfaces and colors. The Accessibility Notes explain what to preserve when making those changes.
Demo
Follow the Complete Submission Cycle. The bug-report demo begins validation on submission and checks edited fields again after that first attempt. It combines schema-backed values with Kamod field presentation, letting you follow one form through invalid input, correction and a submission attempt.
Replace the demonstration submission with your own request and distinguish Field Errors from Service Failures. Preserve useful input after a failed save, give the user an actionable message and verify that a retry cannot create duplicate work.
Interactive preview
Preact example Local preview theme · Responsive styles follow the preview widthFull widthInput
Keep Browser Input and Form State Synchronized. Spread field.props onto the native input so its events stay connected to the form store. Normalize an absent text value to '' for controlled rendering while keeping the user's actual input as the source of the displayed value.
Preserve the label, description and error associations when adding styling; changing the wrapper should not break the field's validation or event binding.
Interactive preview
Preact example Local preview theme · Responsive styles follow the preview widthFull widthTextarea
Guide the Answer without Competing with Validation. Bind a textarea to the same Formisch field model used for a single-line input. A nearby character counter can explain how the answer relates to a limit, provided it reads the same value that validation checks.
Explain whether the limit counts characters, words or another unit, and ensure the counter follows that rule. Leave room for longer answers and visible error messages, then test the point where an answer becomes valid again after editing.
Interactive preview
Preact example Local preview theme · Responsive styles follow the preview widthFull widthSelect
Bridge the Composite Control Explicitly. Pass field.input into a composite select and forward its value callback to field.onChange. This explicit bridge connects the control's selection model to Formisch rather than expecting native input events from a custom trigger.
Use stable option values, handle an initially empty selection deliberately, and keep the label attached to the trigger rather than only to the surrounding layout.
Interactive preview
Preact example Local preview theme · Responsive styles follow the preview widthFull widthCheckbox
Treat the Selected Options as One Field Value. Store a checkbox collection as an array of selected values and create a new array for every change. Adding with a spread and removing with filter keeps updates explicit for the form store and its validation.
Use stable values for each checkbox, derive checked state from that array, and place collection-level validation where it is clear which group needs attention.
Interactive preview
Preact example Local preview theme · Responsive styles follow the preview widthFull widthRadio Group
Keep the Allowed Values Aligned with the Schema. Connect RadioGroup to one field value whose allowed strings match a Valibot picklist. The selected option and submitted data then share the same vocabulary, avoiding a separate translation between visual labels and accepted values.
Drive the group from the field's current input and forward changes directly, rather than maintaining another selection state beside the form.
Interactive preview
Preact example Local preview theme · Responsive styles follow the preview widthFull widthSwitch
Preserve a Boolean Throughout the Binding. Drive Switch from the field's boolean input and send changes back to that same field. The visual on/off state becomes a direct view of the value Formisch will validate and include in submission.
Explain the enabled state in the label and distinguish immediate settings from preferences saved on submit; the visual toggle alone does not decide that workflow.
Interactive preview
Preact example Local preview theme · Responsive styles follow the preview widthFull widthComplex Forms
Compose Larger Workflows from the Same Small Bindings. Build a larger form by grouping the same field primitives around plan, billing and preference choices. Each section adds context to the shared form state rather than creating independent stores for pieces of one submission.
Inspect the submitted shape alongside the schema, and avoid duplicating form state in presentation components when a value already belongs to Formisch.
Interactive preview
Preact example Local preview theme · Responsive styles follow the preview widthFull widthResetting the Form
Make the Reset Destination Predictable. Call reset(form) to restore the initial inputs and clear validation state when the user deliberately starts over. Give the reset control type="button" so activating it does not also trigger the form's submit path.
Keep reset separate from submission, and verify that validation feedback and derived summaries reflect the restored values rather than retaining stale state outside the form.
reset(form) resets the form store. The demo also clears its separately stored result. In your app, decide whether reset should clear a request error or restore freshly loaded server values. The preview toolbar’s Reset remounts only that example and retains its selected container width.
Interactive preview
Preact example Local preview theme · Responsive styles follow the preview widthFull widthArray Fields
Preserve Identity While Rows Move or Disappear. Use FieldArray item IDs as stable row keys, and manage the collection with insert and remove. Valibot can enforce allowed lengths while each row retains its identity as neighboring entries are added or removed.
Associate each row's labels and errors with the correct field, and test removing a middle row so another person's entered values do not appear to jump between controls.
Keep Row Identity Separate from Field Position: key rows by the IDs from array.items.value, and bind fields with their current index. Check removal in the middle of the list, an empty new row, the five-row limit and keyboard focus after removal.
Interactive preview
Preact example Local preview theme · Responsive styles follow the preview widthFull widthHow the Pieces Work Together
Build around One Form Store, with a clear role for each layer. Valibot describes valid data, Formisch coordinates the interaction, and Kamod UI gives it a familiar interface. Your application connects the result to a real service. Start with the Complete Example, then use these boundaries as you adapt it.
Start with the Data
Describe accepted values and useful error messages in a Shared Schema. Infer the submitted type with v.InferOutput so your handler stays connected to the same rules as your fields.
Keep State in One Place
Create the store with useForm. Read each field’s value and errors from that store, then choose When to Validate with validate and revalidate. Reset and submission use that same state.
Make Every State Clear
Compose a visible label, control and feedback with Field. Connect error messages to the input and set aria-invalid when needed. Preserve Labels and Keyboard Behavior as you refine the layout.
Carry the Result through
Use onSubmit to connect validated output to your request. Your service handles authorization and server validation; your interface explains pending, success and failure states. Keep Entered Values available after a failed save so the person can retry.
Form Methods
Import only the methods you need. The methods API can inspect, validate, submit, reset, focus, and update deeply nested fields or field arrays.
The following lines are independent operations on an existing form, with schema and initialInput supplied by your component. Do not execute the whole list during render. Call mutations from the relevant event handler.
import { Field as FormischField, FieldArray, Form as FormischForm, insert, remove, reset, useForm } from "@formisch/preact";
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Checkbox, Field, FieldDescription, FieldError, FieldGroup, FieldLabel, FieldLegend, FieldSet, Input, RadioGroup, RadioGroupItem, Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue, Switch, Textarea } from "@kamod-ch/ui";
import * as v from "valibot";
import { focus, getErrors, getInput, move, replace, setErrors, setInput, submit, swap, validate } from "@formisch/preact";
const form = useForm({ schema, initialInput, validate: "submit", revalidate: "input" });
getInput(form, { path: ["email"] });
setInput(form, { path: ["email"], input: "hello@kamod.ch" });
getErrors(form, { path: ["email"] });
setErrors(form, { path: ["email"], errors: ["Use a work email."] });
await validate(form, { shouldFocus: true });
submit(form);
focus(form, { path: ["email"] });
insert(form, { path: ["emails"], at: 0, initialInput: "" });
remove(form, { path: ["emails"], at: 0 });
move(form, { path: ["emails"], from: 0, to: 1 });
swap(form, { path: ["emails"], at: 0, and: 1 });
replace(form, { path: ["emails"], at: 0, initialInput: "team@kamod.ch" });
reset(form);Props and Data
Configure Formisch using the contracts below. Read the documented options alongside the Source Definitions to understand which values your application supplies and which details the component owns. Start with a prop or helper, then follow its type link to inspect the declaration without leaving the page.
The most important integration APIs are useForm, Form, Field, FieldArray, reset, insert, remove, and the optional methods shown below.
Type cards are extracted from this checkout’s TypeScript source at build time. Props inherited through HTMLAttributes, Omit or variant helpers remain references in those declarations; their fields are not flattened here. Match the reference to your installed version, and check a package’s exports before writing an import type. A type exported by a source file is not necessarily re-exported by @kamod-ch/ui.
Form Props and Contracts
? means a field can be omitted; it does not promise a fallback value. Existing documented defaults remain alongside the descriptions. For callbacks, check the argument and return types before connecting your own state or services.Example
The local demonstration wrappers accept an ID prefix so labels and controls stay unique when several examples appear on one page. This is a demo contract, not a prop of FormischForm.
| Prop / type | Description |
|---|---|
idPrefix | A unique prefix used to build the form and control IDs in each example. Supply a different prefix for every mounted instance to preserve label associations.
|
The following integration points come from @formisch/preact. They describe the roles used throughout the examples; follow the package reference for their complete generic signatures.
| Prop / type | Description |
|---|---|
useForm | Create a form store from a Valibot schema and initialInput; choose validate and revalidate timing. |
Form | Pass the store with of and handle validated output in onSubmit. The service request remains yours. |
Field | Use a typed path. Read input.value and errors.value; preserve native field.props or wire a composite control's callback. |
FieldArray | Read items.value and use each stable item ID as the row key; use the current index in the field path. |
reset | Restore initial inputs and clear form validation state. Reset any separate request or result state yourself. |
insert / remove | Change rows through the form store so array state and validation stay connected. |
This is an integration map, not a replacement for the Formisch API Documentation. Check the installed version before adopting optional methods.
Data Type Reference
Expand a card to inspect and copy the exact declaration. The code header identifies its repository file; follow imported or inherited types in the Implementation Source when you need the complete dependency chain. Required-field summaries cover fields declared directly in that type. Source-only helpers and inferred schema outputs describe the local implementation, not additional props you can pass to every component.
Example Props
1 declared fieldExamplePropsFormischExamples.tsx. Referenced types retain their original names; inspect that file for imports and supporting definitions. Inspect the Complete Definition of ExampleProps before adapting it.idPrefixBugReportOutput
DeclarationBugReportOutputFormischExamples.tsx. Referenced types retain their original names; inspect that file for imports and supporting definitions. Inspect the Complete Definition of BugReportOutput before adapting it.Anatomy
A typical form has a Valibot schema, a useForm call, a FormischForm, one or more FormischField blocks, Kamod Field wrappers, visible errors, and action buttons.
- Define the schema and create the store inside the form component.
- Wrap fields in
FormischFormand give every control a stable label association. - Bind the field value, display its errors and distinguish submit actions from secondary buttons.
- Use validated output for your request; keep pending, failure and success feedback visible.
Schema and Form Setup
Valibot is the single source of truth. Input and output types are inferred from the schema, so submit handlers receive validated data.
import * as v from "valibot";
export const ContactSchema = v.object({
email: v.pipe(v.string(), v.email("Enter a valid email address.")),
});
export type ContactOutput = v.InferOutput<typeof ContactSchema>;Pass this schema to useForm with initialInput: { email: "" }. Keep the schema outside the component when its rules are static, and the form store inside the component that owns the interaction.
Validation
Use Valibot pipes for length, email, picklist, array, and boolean constraints. Formisch returns field-level error strings that map directly to FieldError.
Client Validation Helps People Correct Mistakes; It Does Not Authorize a Request. Validate submitted data again on the server. Keep network or permission failures distinct from field constraints, and preserve the entered values so the user can recover.
Validation Modes
Choose when the first validation happens with validate, and when later checks happen with revalidate.
The snippets below compare options for an existing schema. Start with validate: "submit" and revalidate: "input" when you want feedback after the first attempt, then prompt correction while editing. Choose blur or live validation deliberately; avoid displaying untouched-field errors before someone has a chance to answer.
const submitOnly = useForm({ schema, validate: "submit" });
const blurFirst = useForm({ schema, validate: "blur", revalidate: "input" });
const live = useForm({ schema, validate: "input" });
const validateImmediately = useForm({ schema, validate: "initial" });
const revalidateOnBlur = useForm({ schema, validate: "submit", revalidate: "blur" });
const revalidateOnSubmit = useForm({ schema, validate: "blur", revalidate: "submit" });Displaying Errors
Set invalid state on Field, aria-invalid on the actual control, and render FieldError only when Formisch has messages.
In the Preact adapter, field.input and field.errors are signals. Read their .value when branching, mapping errors or passing a primitive into a controlled input.
// Inside a FormischField render callback:
const value = typeof field.input.value === "string" ? field.input.value : "";
const invalid = Boolean(field.errors.value?.length);
const errors = field.errors.value?.map((message) => ({ message }));Keep FieldLabel, the input ID and any aria-describedby targets in sync. A red border alone is not an error message. Use unique IDs if the same form appears more than once.
Accessibility
Build the Complete Interaction, Including the Parts Outside Formisch. The notes below distinguish the current implementation from the labels, content and behavior your application supplies. Start with the Live Preview, check the Props and Data Reference, and test the finished composition with real content rather than assuming that an unchanged visual example covers every use case.
Built-in Behavior and Defaults
Formisch manages typed field state and validation through a store; Kamod provides the rendered controls and field layout. In the Preact adapter, field.input and field.errors are signals, so read their .value when choosing displayed values or messages. Neither a schema nor a red field wrapper automatically supplies an accessible name, an error-description relationship or an appropriate focus destination. The examples use explicit IDs and labels; review each control's rendered HTML when adapting them. Preserve field.props for native inputs, and use the demonstrated value/change binding for composite controls rather than assuming every component accepts the same event contract.
Labels and Relationships
Give every input a visible FieldLabel whose htmlFor matches the real input or labelable trigger ID. Use useId or an instance-specific prefix so repeated forms do not compete for the same label. Add IDs to persistent help text and FieldError, then reference the applicable IDs with aria-describedby on the actual control. Keep instructions available before submission and make corrections specific: Enter a valid email address is more useful than Invalid input. For grouped choices, use FieldSet/FieldLegend and individual option labels; a group question is not a replacement for each option's name. Put required, disabled and aria-invalid on controls where appropriate, not only on the visual Field wrapper.
Connect the Visible Error to the Real Input. This is a fragment for an existing FormischField render callback, not a standalone form. Your store must include a string email field; define a unique id in the owning component. Preserve the native handlers while adding explicit label/error relationships.
import { Field, FieldLabel, FieldError, Input } from "@kamod-ch/ui";
// Inside your existing typed FormischField render callback:
// field is supplied by <FormischField of={form} path={["email"]}>.
const invalid = Boolean(field.errors.value?.length);
const helpId = `${id}-help`;
const errorId = `${id}-error`;
return (
<Field invalid={invalid}>
<FieldLabel htmlFor={id}>Email address</FieldLabel>
<Input {...field.props} id={id} type="email" autoComplete="email"
value={typeof field.input.value === "string" ? field.input.value : ""}
aria-invalid={invalid || undefined}
aria-describedby={[helpId, invalid ? errorId : undefined].filter(Boolean).join(" ")} />
<p id={helpId}>Use an address where you can receive account updates.</p>
{invalid && <FieldError id={errorId}
errors={field.errors.value?.map((message) => ({ message }))} />}
</Field>
);Keyboard and Focus
Choose validation timing deliberately. A submit-first flow lets someone complete a field before being shown an error; revalidation on input can then help them correct it. After an unsuccessful submission, verify where Formisch's focus behavior lands for native inputs and for custom triggers; do not add a competing focus effect blindly. For a long form, consider a focused error summary with links to affected controls when inline feedback alone leaves errors hard to find. Do not move focus after each keystroke. In FieldArray, key rows by the stable IDs in array.items.value while using the current index for the field path. After adding or removing a row, choose an appropriate surviving field or Add action, and ensure each removal button identifies its row.
States and Integration Details
Treat schema errors, server-rejected values and network failures as distinct outcomes. Preserve entered data after a rejected request and give a visible retry path. During submission, show meaningful pending text and prevent duplicate requests without stranding focus on a removed button. A disabled button alone does not explain progress. FieldError already has alert semantics; avoid wrapping every error in another assertive live region or repeatedly announcing the same message from both a summary and each field. Keep success visible near the form when the task stays on the page. When resetting, clear any application-owned request/result state deliberately as well as resetting the form store, and explain destructive resets when they would discard substantial work.
Verify the Complete Interaction
Check Behavior as Well as Markup. Work through these scenarios in the application where the component will be used. Automated checks can help find structural problems; also review the reading experience with a screen reader, keyboard focus and the actual feedback from your application.
- Submit an untouched form, correct one error at a time, then submit valid data. Verify label, required state, help text and error text for both native fields and custom select/switch triggers with a screen reader.
- Add several array rows, remove the middle row and reorder if supported. Confirm stable input identity, unique IDs, correct remaining values and a sensible focus destination after the focused row disappears.
- Simulate slow submission, server validation failure, network rejection, retry and reset. Keep values recoverable, feedback understandable and all actions reachable at narrow widths, enlarged text and in both themes.
Recheck the result after changing Theme Tokens, translations or class overrides. Include text enlargement, narrow layouts and reduced-motion settings where animation is present. Inspect the Component Source when a behavior differs from your expectation; a role or state attribute does not implement keyboard interaction by itself.
For background, read the WAI-ARIA Authoring Guidance and the WAI Guide to Form Feedback. These explain the patterns; verify browser and assistive-technology behavior for the implementation and audience you actually support.
Sources
Related references for the ideas and APIs used on this page.
The original shadcn/ui Formisch Guide is a reference for the form patterns. Its examples use React; this page integrates @formisch/preact with Kamod’s Preact components. Consult Formisch for form APIs and Valibot for schema APIs, and check each project’s license when reusing source.
Connect It to Your Data
Keep the schema output at the service boundary. Pass your own onSubmit and return its promise so the form can track the submission. Show request errors beside the form, and reset only after a confirmed success.
import type { InferOutput } from "valibot";
import { ContactSchema } from "./contact-schema";
type ContactOutput = InferOutput<typeof ContactSchema>;
// Pass a typed service into the form instead of embedding a demo endpoint.
type ContactFormProps = {
onSubmit: (values: ContactOutput) => Promise<void>;
};
// Inside your form component, keep the submission promise connected:
// <FormischForm of={form} onSubmit={(values) => onSubmit(values)}>
// ...fields and a submit button...
// </FormischForm>You have the pieces. Put them into one real interaction, keep its state in one place, and check the result with the content your application will actually show.
Connect the Foundation
Return to Connect Fields, Validation and Submission to connect this reference to a working screen. Keep global CSS in one entrypoint and import only the components that screen needs.
Build the Surrounding Screen
Find a neighboring interaction in the Component Library, or start with a complete Block. Replace sample content and destinations before refining the layout; a local class change can stay with the composition.
Make the Result Hold Up
Use shared theme roles for changes that belong everywhere. Then review the whole journey: keyboard focus, long labels, narrow screens and a clear way to recover when something fails.
Keep a link to the source and note your intentional changes. Your next edit should begin with a clear decision, not another search.