# Attaform documentation > The full text of every Attaform documentation page, concatenated for AI agents. Regenerated from the docs on every build. The curated index lives at https://attaform.dev/llms.txt. --- # Introduction > One Zod schema, one Attaform, one source of truth. Attaform reads a Zod schema and hands back the form, ready to play: reactive `values`, per-field `errors`, a `meta` aggregate, and a `v-register` directive that binds every native input shape. **Your schema is the form.** The schema is the validator. The schema is the API contract. Type-safe end to end. Errors surface at compile time, and the runtime keeps every value matched to what your schema declared. Server errors flow back through the same reactive surface, SSR hydrates without flashes, and the panel inside Nuxt DevTools shows every form on the page. ## How these docs read The sidebar walks top to bottom as a learning narrative: install, schema, bind, validate, submit, then read and mutate the form. Drop in anywhere. Every concept is its own URL, its own definition, its own demo. If you're new, start with the [Quick start](/docs/getting-started/quick-start). If you want our philosophy first, read [Why Attaform](/docs/getting-started/why-attaform); if you want the receipts, [Benchmarks](/docs/comparison/benchmarks) measures Attaform against the Vue form-library field in a real browser. If you're hunting a specific surface, the sidebar's last category, **Reference**, is alphabetical and indexed. Reading with a coding assistant? These docs are machine-readable too. Point it at [`llms.txt`](/llms.txt) for the whole index, or install the [Agent Skill](/docs/ai-tooling/agent-skill) so it writes idiomatic Attaform from the first try. The [AI tooling](/docs/ai-tooling/agent-skill) pages lay out every option. _Source: https://attaform.dev/docs/getting-started/introduction_ --- # Why Attaform > Five marks of a great form library. Attaform's North star, top to bottom. Forms look simple from the outside. Inside, they're a thicket of subtle details: blank-value tracking, coercing DOM strings back to the types a schema declared, SSR, async validation, nested objects and discriminated unions, efficient DOM tracking, errors flowing from validators and your server into one reactive form API. A great library handles every one for you, without making you reach for the type plumbing or wire up the side-channels yourself. These five convictions guide Attaform's design: 1. **Telepathically accurate type safety.** Types flow from your schema into every surface: values, errors, paths, write shapes, etc. We don't do `any`. 2. **A tiny, predictable API that just works.** Small surface, no surprises. If you can't learn the core API in five minutes, it's not good enough. 3. **Stays out of your markup.** One directive, `v-register`, does the heavy lifting. Your `` stays a native ``; nothing sits between the DOM and the form. 4. **Vue conventions, end to end.** Composables, reactivity, directives: the shapes you already know. 5. **The schema drives everything.** Data shape, defaults, validation, errors, and types. All from one Zod schema. Why? Because at the end of the day, Vue and Nuxt devs deserve nice things too. ## One source of truth: your schema Write a Zod schema. That's the source of truth for: - **Types.** Every path, value, error, and write shape is inferred. No `any`, no manual generics, no reaching for the type plumbing whenever you add a field. - **Defaults.** Attaform reads the schema's slim shape (`''` for strings, `0` for numbers, `false` for booleans) and uses it as the storage default. Override per field; don't repeat what the schema already says. - **Validation.** Refinements run synchronously by default; async refinements await before submit dispatches. - **Errors.** Each one lands at the offending path. `form.errors.email` is reactive end-to-end. - **Metadata.** Labels, descriptions, placeholders, and free-form meta attach to schema fields and surface on `form.fields.`. One schema in, full reactive surface out. ## Type-safe end to end Every part of the public surface is typed against your schema: ```ts const schema = z.object({ email: z.email(), age: z.number().int().min(13), }) const form = useForm({ schema }) form.setValue('age', 21) // ok form.setValue('age', 'twenty-one') // type error ``` `form.fields.` knows the exact set of paths in the schema. `form.errors.` is reactive, typed, narrowable. The types follow the form through every state. While the user is typing, `form.values` is wide enough to hold whatever they have put there so far: incomplete fields, undecided discriminators, rehydrated half-filled draft state from yesterday's session. Inside `handleSubmit`, the same data flows through the schema and emerges with literals narrowed, refinements honored, and discriminated unions discriminating. Wide where reality is wide, tight where the schema guarantees it. [Type safety](/docs/reading-the-form/type-safety) walks through the trade. ## Native inputs, Vue directive `v-register` is a Vue directive, not a wrapper component. Your `` stays a native ``; there's no field-component overhead between the DOM and the form. ```vue ``` That's the whole binding, and the element on the page is still the one you wrote. `v-register` wires value sync, focus and blur state, blank tracking, and the a11y attributes onto it in place. ## Live, layered validation - Per-field on `change`, `blur`, or `submit`. Your call, per form. - Sync refinements fire on the keystroke; async refinements await. - A form's `meta.valid` is _gated_. It only flips true after every active path has resolved at least one validation pass, including the async ones. No flash-of-valid window for users with a slow uniqueness check. - Server-side errors map back into the same reactive form API. The render surface is the same whether the error came from Zod or your API. ## SSR-first, hydration-clean Forms render server-side and hydrate without a flash: values, both error layers, and every per-field flag ride the payload, so the form your server rendered _is_ the form your client picks up. Nuxt is zero-config. Bare Vue 3 with `@vue/server-renderer` is two helpers, one per side of the boundary, plus the build plugin that teaches the compiler to render a component-wrapped input's state on the server. ## Built into the core These ship with the core, typed and orchestrated as first-class features: - Field arrays with stable keys and per-item validation. - Undo / redo with bounded history, opt-in per form. - Discriminated unions with variant memory across discriminator switches. - Multistep wizards that compose plain `useForm` calls, with a hard-prerequisite `gate` and URL sync. - A one-option data freeze: `useForm({ disabled })` no-ops every write at the source, so a read-only screen cannot be written around. - A DevTools panel that surfaces every form on the page: values, errors, history. ## Where to next - [Quick start](/docs/getting-started/quick-start): your first form, end-to-end. - [The form](/docs/reading-the-form/the-form): the full reactive surface returned by `useForm`. - [Type safety](/docs/reading-the-form/type-safety): wide while typing, tight inside `handleSubmit`, by design. - [When validation runs](/docs/validation/when-validation-runs): the moment errors appear. - [The `v-register` directive](/docs/binding-inputs/v-register): how Attaform binds inputs. - [Benchmarks](/docs/comparison/benchmarks): how Attaform measures up across the Vue form-library field, in a real browser. _Source: https://attaform.dev/docs/getting-started/why-attaform_ --- # Installation > One command. Attaform bootstraps itself. Install Attaform and Zod, and you're set. `useForm` bootstraps itself the moment the package lands: no plugin call, no provider wrapper. The [Nuxt module](#nuxt-module) and the [Vite plugin](#vite-plugin-bare-vue-3--vite) complete the picture by binding `v-register` into your templates at compile time; building without either, the [one-liner below](#no-build-plugin) delivers the directive instead. ## Nuxt module If you're on Nuxt, we recommend installing the module: ```ts // nuxt.config.ts export default defineNuxtConfig({ modules: ['attaform/nuxt'], }) ``` What this gets you: the form composables as auto-imports (`useForm`, `useWizard`, `injectForm`, `injectWizard`, `fieldMeta`, `withMeta`, `lazy`, `gate`, and `useRegister`; see [Auto-imports](#auto-imports)), `v-register` bound into every template that uses it, the SSR hydration plumbing, the Vite plugin, and the Attaform tab inside Nuxt DevTools. ## Optional: Vue 3 plugin `useForm` installs Attaform on first use, so a bare Vue 3 app needs no entry-file wiring at all. Install the plugin explicitly when you want control over registration order, or when you need one of its app-wide switches: ```ts import { createApp } from 'vue' import { createAttaform } from 'attaform' import App from './App.vue' createApp(App) .use(createAttaform({ devtools: false })) .mount('#app') ``` What this gets you: `devtools: false` to skip the Vue DevTools integration even in development, and `ssr: true` for a server entry, which the SSR serialization helpers require. ## Vite plugin (bare Vue 3 + Vite) If you're on bare Vue 3 + Vite (not Nuxt), add the plugin to `vite.config.ts`: ```ts import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { attaform } from 'attaform/vite' export default defineConfig({ plugins: [vue(), attaform()], }) ``` What this gets you: `v-register` bound into every template that uses it (no app-level registration to write), SSR-rendered `v-register` bindings that match the client-rendered output on initial HTML (no flicker between server paint and hydration), and a leaner production bundle (one Zod adapter shipped instead of both). ## No build plugin? Building with a webpack-family bundler, importing from a CDN, or compiling templates at runtime? Register the directive once per app: ```ts import { createApp } from 'vue' import { installVRegister } from 'attaform/directive' import App from './App.vue' const app = createApp(App) installVRegister(app) app.mount('#app') ``` The bundler plugins at `attaform/webpack`, `attaform/rspack`, `attaform/rollup`, and `attaform/esbuild` still handle the single-Zod-adapter rewrite for their pipelines; `installVRegister` covers the directive. Client-rendered apps need nothing further. The one piece that does not travel is the compile-time template work, which is `@vitejs/plugin-vue`-specific: if you server-render, wire [`attaform/transforms`](/docs/reference/entry-points#attaformtransforms) into your Vue compiler so the server paints each bound input's state rather than leaving hydration to fix it. ## Auto-imports Both the Nuxt module and the Vite plugin can register Attaform's form composables as auto-imports, so a component reaches for them inside ` ``` The [segment-array form](/docs/writing-and-mutating/set-value#three-call-shapes) does the same job without the template literal, and is the better read when the prefix is assembled from separate variables: ```ts import { useForm } from 'attaform' import { z } from 'zod' const schema = z.object({ boxes: z.array(z.object({ pairs: z.record(z.string(), z.string()) })), }) const form = useForm({ schema, key: 'pdf' }) declare const index: number declare const token: string form.register(['boxes', index, 'pairs', token]) ``` ## Mutating records Records don't expose field-array helpers (`append` / `remove` / etc.); they're keyed dictionaries, not ordered sequences. Mutate them via `setValue` directly: ```ts form.setValue(`prefs.${userId}`, true) // set / overwrite one entry form.setValue('prefs', { ...form.values.prefs, [userId]: true }) // whole-record merge ``` To flag a record entry blank, reach for `unset`: ```ts import { unset } from 'attaform' form.setValue(`prefs.${userId}`, unset) ``` `unset` at a record entry writes the value schema's slim default at the path and adds the path to `form.blankPaths`. The bound input renders empty, and a required value schema surfaces `atta:no-value-supplied` reactively. To clear the whole record back to `{}`, pass `unset` at the record container: `form.setValue('prefs', unset)`. ## `z.map(keySchema, valueSchema)` Map is the primitive `Map`, distinct from records (which are plain JS objects): ```ts const schema = z.object({ scoresByUser: z.map(z.string(), z.number()), }) const form = useForm({ schema, defaultValues: { scoresByUser: new Map() }, }) form.values.scoresByUser // Map form.values.scoresByUser.get('user-42') // number | undefined ``` `form.values.scoresByUser` returns the live `Map`, and you call its methods directly. Each entry is also a path in its own right, so `form.register`, `form.setValue`, `form.fields` and `form.errors` all address one the same way they address a record entry: ```ts form.setValue('scoresByUser.user-42', 90) form.fields.scoresByUser['user-42'].dirty // true form.errors.scoresByUser['user-42'] // ValidationError[] ``` The key type you declared decides how a path segment is spelled. A path segment that looks like an integer arrives as a number, so under `z.map(z.string(), V)` the segment `'42'` files the entry under the string `'42'`, and under `z.map(z.number(), V)` it files it under the number `42`. Either way the same path reads it back. A map keyed by something a path cannot spell (an object, a symbol) has no addressable entries, and stays one whole value. Use map (over record) when: - You need `Map`-specific semantics: insertion order, key types beyond strings, or `.size` as an O(1) read. - You save the form's values through a structured-clone channel (IndexedDB, a worker `postMessage`) and want fidelity. `JSON.stringify` flattens a `Map` to `{}`; structured clone preserves it. Records are the right call for serialization-friendly dictionaries; maps are right when you need the primitive. ## Iterating in templates For records, iterate over `Object.entries`: ```vue ``` For maps, iterate the `Map` directly: ```vue ``` The template renders re-run when the underlying record / map updates because `form.values` proxies through the reactivity layer. ## Errors per entry Errors land at the keyed path, the same as array elements: ```ts form.errors.prefs['user-42'] // ValidationError[] (empty when no errors) form.errors.scoresByUser['user-99'] // (works for maps too) ``` The aggregate `form.meta.errors` flattens every entry's errors into one list, in path order. ## A note on `z.set` A set is the one container whose contents are not paths. A set member is its own key, so there is no address that survives writing to one: change the member and you have changed where it lives. `form.fields.tags[0]` resolves nothing, and a write to `tags.0` is refused rather than applied. Read a set through `form.values`, and write it whole: ```ts form.values.tags // Set form.setValue('tags', new Set([...form.values.tags, 'new-tag'])) ``` A validation error on a member lands on the set itself rather than on any member, on both Zod majors. That makes it a container-self error, so `form.errors.tags` navigates to the set's sub-Proxy and the list lives one step further on, at the [`''` sentinel](/docs/reading-the-form/errors#the-sentinel-container-self-errors): ```ts form.errors.tags[''] // ValidationError[]: the set's own form.errors('tags') // the same list, through the flat call form form.fields('tags').firstOwnError // the first one, display gating included ``` ## When to pick which - **`z.record(z.string(), V)`**: string-keyed dictionaries serialized as JSON. The default choice. - **`z.record(z.enum([...]), V)`**: keys constrained to a small set. Compile-time autocomplete on the keys. - **`z.map(K, V)`**: when you need `Map`'s insertion order, non-string keys, or structured-clone fidelity for IndexedDB persistence. - **`z.object({ … })`**: when the keys are fixed and known at schema-write time. Records are for the dynamic case. When the record is the entire form rather than a field inside one, reach for a [dictionary form](/docs/schemas/dictionary-forms): the `z.record` becomes the schema root, `form.values` is the map itself, and `form.record()` iterates it. ## Where to next - [Dictionary forms](/docs/schemas/dictionary-forms): a `z.record` schema as the form root, not just a field inside an object. - [Arrays & tuples](/docs/schemas/arrays-and-tuples): numeric-keyed sequences; the other half of the "many-items" picture. - [Nested objects](/docs/schemas/nested-objects): fixed-shape composition; the alternative when keys are known. - [`unset`, the blank-anywhere sentinel](/docs/writing-and-mutating/unset): how to flag a single record entry blank, or wipe the whole record back to `{}`. _Source: https://attaform.dev/docs/schemas/records_ --- # Dictionary forms > When the form _is_ a map, make the map the root. A `z.record` schema at the top level gives you a dictionary form: `form.values` is the map itself, and `form.record()` iterates its entries. The demo is a team roster keyed by member id. The ids are data you only learn at run time, so the schema root is a `z.record(z.string(), …)`, a string-keyed dictionary of members. The whole form is that map: edit a member, add one, drop one, and watch `form.values` track it below. ## The schema A dictionary form declares a `z.record` schema as the root, not nested under a key. The key schema constrains what counts as a valid key; the value schema validates each entry: ```ts import { useForm } from 'attaform' import { z } from 'zod' const schema = z.record( z.string(), z.object({ role: z.enum(['admin', 'editor', 'viewer']), tier: z.number() }) ) const form = useForm({ schema }) ``` There is no wrapper key. `form.values` reads as `Record`, the map itself. ## `form.values` is the dictionary Because the record is the root, `form.values` is the whole map, and entries bind through their own key: ```ts form.values() // the whole map: Record form.values()['ada'] // one entry, or undefined form.register('ada.role') // bind an entry sub-field form.errors['ada']?.['tier'] // ValidationError[] for that entry's tier ``` The `| undefined` on an entry read comes from `noUncheckedIndexedAccess`, the same way a record field reads anywhere else. Reach for `??` defaults at the call site when you need one. ## Iterating with `form.record()` `form.record()` with no argument is the root entry view: one [`FieldState`](/docs/reading-the-form/fields) per entry, keyed by the entry's own key. It is the root counterpart of [`form.record(path)`](/docs/reading-the-form/record), which views a nested record. The keys come from the form, so you render whatever entries exist without keeping a parallel list of your own: ```vue ``` Each `member` is a live `FieldState`, the same surface [`form.fields`](/docs/reading-the-form/fields) exposes, so every read stays current as the user types. Binding still flows through [`form.register`](/docs/binding-inputs/v-register) with the entry path, which the key supplies. ## Adding, editing, and removing entries A dictionary form carries its own keys, so you grow and shrink it through [`setValue`](/docs/writing-and-mutating/set-value). Editing and adding are ordinary path writes: ```ts form.setValue('ada.tier', 4) // edit one entry's field form.setValue('mae', { role: 'viewer', tier: 1 }) // add a key that isn't there yet ``` Removing is the one case the root changes. A nested record drops a key by rewriting its container path; a record root has no container path, so you rewrite the form itself. Passing a single argument to `setValue` is a whole-form write, and for a dictionary form the whole form is the map: ```ts const next = { ...form.values() } delete next['ada'] form.setValue(next) // write the map back without that key ``` Surviving entries keep their field states and component instances across the write; only the dropped row unmounts. ## Defaults A bare record root defaults to an empty map, ready to grow: ```ts const form = useForm({ schema }) form.values() // {} ``` Seed initial entries with `defaultValues`, the same shape as the form value: ```ts const form = useForm({ schema, defaultValues: { ada: { role: 'admin', tier: 3 } }, }) ``` ## When the keys are fixed, reach for an object Dictionary forms are for keys you learn at run time. When the keys are known at schema-write time, a `z.object` root is the better fit: fixed keys, a distinct type per field, and compile-time autocomplete on each one. The two compose freely. An object form can hold a `z.record` field (see [Records & maps](/docs/schemas/records)), and a dictionary form's value schema can be any Zod schema, including objects, arrays, and nested records. ## Where to next - [Records & maps](/docs/schemas/records): `z.record` as a field inside an object form, plus the `z.map` primitive. - [`record`](/docs/reading-the-form/record): the entry view, `form.record(path)` for a nested record and `form.record()` for the root. - [`setValue`](/docs/writing-and-mutating/set-value): the writes that grow, edit, and shrink a dictionary. - [Nested objects](/docs/schemas/nested-objects): fixed-shape composition, the alternative when the keys are known. _Source: https://attaform.dev/docs/schemas/dictionary-forms_ --- # Nested objects > Schemas compose by nesting: one `z.object` inside another. The proxy descends through dot-paths so `form.values.profile.name`, `form.errors.profile.name`, and `register('profile.name')` all work the way you'd expect. This page is code-only; every other demo in the docs already nests objects. The shape, the proxy, and the path semantics are best understood through the snippets below; reach for a real demo on [Arrays & tuples](/docs/schemas/arrays-and-tuples) (which composes arrays of nested objects) or [Discriminated unions](/docs/schemas/discriminated-unions) (which nests variant objects inside the outer union) when you want to see it live. ## The shape ```ts const schema = z.object({ profile: z.object({ name: z.string().min(1, 'Name is required'), bio: z.string().optional(), }), address: z.object({ line1: z.string().min(1, 'Street is required'), city: z.string(), postalCode: z.string(), }), }) const form = useForm({ schema }) ``` Each leaf gets its own path: ```ts form.values.profile.name // string form.values.address.city // string form.register('profile.name') // path autocomplete narrows the union form.errors.address.postalCode // readonly ValidationError[] ``` ## The proxy descends transparently `form.values`, `form.errors`, and `form.fields` are all proxies; `form.values.profile.name` resolves through one descend per dot segment. The reactivity tracks at the path level, not the leaf level: re-running templates only fires for paths whose values changed. ```vue