Every Part of a Form Is a Form

Most of the forms I work on aren't filled in once and submitted in one go. They come in steps, they hold lists, some fields only matter after a certain answer, and some rules can only be answered by the server. We build them with vee-validate and Zod, and for a form with a single submit, that pair is great.
The product team kept asking for forms that needed more than a single submit, and each time our answer was another workaround. After enough of them, I started to see the same problem behind all of them.
The Form
Take a form for publishing a workshop. It isn't one of ours, but it has the same shape, and we ran into every problem in it.
It has two steps. The details hold a title, a URL and a format, plus a venue for in-person workshops. The schedule is a list of sessions, each with a date and a number of seats. The URL has to be free, two sessions can't share a date, and the organizer's plan caps the total seats.
Publish sends everything in one request. Later, on the edit page, a single session can be saved on its own.
vee-validate follows the browser's model of a form. A form has one root: fields register into it, the schema belongs to it, and its submit validates all of it.
const { handleSubmit } = useForm({
validationSchema: toTypedSchema(workshopSchema),
})
const publish = handleSubmit(api.publishWorkshop)That's the right model for most forms. This one needs smaller submits too, one for a step and one for a single session, and each of them turned into a workaround.
Steps That Can't Be Forms
Next should check only the current step. The obvious idea is to make every step a form of its own inside the wizard's form. HTML doesn't allow that:
<form @submit.prevent="publish">
<form @submit.prevent="next">
<!-- a browser drops this inner form tag -->
</form>
</form>So we did what most wizards do. Each step has its own vee-validate form that keeps its values after unmounting. The steps still make up one workshop, so every step's submit copies its values into a form state kept in a store, and Publish sends that state:
const formStateStore = useFormStateStore()
const { handleSubmit } = useForm({
validationSchema: toTypedSchema(detailsSchema),
keepValuesOnUnmount: true,
})
const next = handleSubmit(details => {
formStateStore.formState.details = details
goTo('schedule')
})The Next button lives in a footer outside the step, and we wired it to next with an event. The browser has a simpler way, because a button doesn't have to be inside a form to submit it:
<form id="details">…</form>
<footer>
<button type="submit" form="details">Next</button>
</footer>The button's form attribute points at the form's id, and the browser connects the two. Keep that attribute in mind. Later on, it's what lets each step stay a plain form.
Saving One Session
Publishing the whole workshop takes one line, the handleSubmit from above. It validates everything and hands over clean, typed values.
On the edit page, the Save button belongs to a single session, and a session isn't a form. Its values live in the workshop's form and its rules are part of that form's schema, so there's no handleSubmit for it. It can't be a form of its own either, because it has to check its date against the other sessions. Saving one session takes all of this instead:
const path = computed(() => `sessions[${toValue(index)}]`)
const { value: session, resetField } = useField<SessionDraft>(path)
const { validateField } = useFormContext()
async function save() {
// each call runs the whole form's schema and keeps one field's errors
const date = await validateField(`${path.value}.date`)
const seats = await validateField(`${path.value}.seats`)
if (!date.valid || !seats.valid) {
return
}
// the parsed values don't come back, so the draft is checked again
const draft = session.value
if (draft.date == undefined || draft.seats == undefined) {
return
}
await api.saveSession({ id: draft.id, date: draft.date, seats: draft.seats })
resetField({ value: draft })
}That's handleSubmit again, rebuilt by hand for one kind of row, and it only knows the fields it names. Add a start time to sessions next month and the schema, the input and the types all pick it up, but Save won't check it until someone remembers to add a third validateField line.
Every list that saves row by row ends up with its own copy like this. What the session needed was a handleSubmit of its own. That sounds like a small ask. It turned out to need a different idea of what a form is.
Rules That Live Elsewhere
The rules collected workarounds of their own.
The venue field is declared optional, and a check on the whole step adds its error back when the workshop is in person:
const detailsSchema = z
.object({
title: z.string().trim().min(1),
format: z.enum(['online', 'in-person']),
venue: venueSchema.optional(),
})
.superRefine((details, ctx) => {
// skipped while any field above is still missing
if (details.format == 'in-person' && details.venue == undefined) {
ctx.addIssue({ code: 'custom', path: ['venue'], message: 'Add a venue' })
}
})Zod skips that check while any other field is still missing, so the error on venue shows up last, after everything else is filled in. It looks like a Zod quirk. It's really about where the venue's rules live, and that turns out to be fixable.
The seat limit doesn't live in the form at all. The rule reads it from the store that holds the plan:
const plan = usePlanStore()
const scheduleSchema = z
.object({ sessions: z.array(sessionSchema) })
.refine(schedule => totalSeats(schedule.sessions) <= plan.seatLimit, {
path: ['sessions'],
message: 'Your plan has fewer seats',
})vee-validate never sees that store. When the organizer upgrades halfway through, the error stays until someone touches a session. The plan doesn't need to be part of the form. The form only needs a way to hear that it changed.
Then there's the url field. Whether a URL is free lives on the server, and a schema can't wait for a request, so the check is split in two. A watcher asks the server once the typing pauses and writes the error into the field, and the schema peeks into the request cache, just to keep the next validation from wiping that error:
watchDebounced(
url,
async value => {
if (await queryClient.fetchQuery(urlTakenQuery(value))) {
setFieldError('url', 'This URL is taken')
}
},
{ debounce: 400 },
)
const urlSchema = z
.string()
.trim()
.refine(value => !queryClient.getQueryData(urlTakenQuery(value).queryKey), { message: 'This URL is taken' })It works, mostly. 😅 Click Next before the answer arrives and the step moves on with a URL nobody checked. And the two halves have to agree on exactly which URL they mean. The watcher asks about what was typed and the schema looks up the trimmed value, so a trailing space is enough for the error to quietly disappear. Both halves exist only because the check has no place of its own in the form.
None of this is a big deal alone. Together it's the same workaround in different clothes. Each one is a part of the form that wants to own something, its submit or its rules, in a library where only the root owns anything.
Looking Around
Being annoyed isn't a reason to write a library, least of all in a space this crowded. Before writing anything, I took a hard look at what was already out there.
vee-validate itself gets the binding right. defineField hands you a model and the props for your input, and the template only binds them:
<script setup lang="ts">
const { defineField } = useForm({ validationSchema })
const [title, titleAttrs] = defineField('title')
</script>
<template>
<input v-model="title" v-bind="titleAttrs" />
</template>The one root is the only part that doesn't fit, and the binding is the part I wanted to keep.
TanStack Form came closest. It can submit a group of fields on its own and debounces its async checks. But a field's rules are written on the field component in the template, and each input is wired to its handlers by hand. I wanted the rules to live with the form and the template to only bind.
So one library had binding that felt right, the other had parts that submit, and neither had both. That's when I started writing my own.
A First Attempt
My first attempt kept one schema for the whole form and added windows on top, letting a step validate and submit by itself:
const form = createForm(workshopSchema)
form.group('details').handleSubmit(details => {
details.url // " Spring-Pottery ", not "spring-pottery"
})It held up until the values. A schema runs as a whole. Validating a step meant running the entire form's schema and keeping the step's errors. Errors survived the trip, values didn't, the same thing validateField does on the edit page, and only the full schema produced the cleaned URL.
Paths were the other problem. Like every form library I'd used, the windows found a part by its path, and a session's path is only its index:
const session = form.group('sessions.1')
form.array('sessions').remove(0)
// session is now the one that used to be thirdErrors and touched fields saved under sessions.1 stay at that path, so they end up on a different session. The composable on the edit page builds its path from the index the same way.
Everything else led back to the root too. The check for url sat on the root by its path, so a step couldn't take its rules along, and every window's type was worked out from every path in the form. The parts were borrowing everything from the root, so they couldn't own anything.
So I deleted it and started over, this time from the parts instead of their paths.
A Tree of Forms
The shape came from an unexpected place. In TanStack Router, each route is defined on its own with its own schema, and the routes are put together into a tree. A route tree isn't a form, of course. Routes can nest because nothing stops them, and forms can't because HTML does, so the comparison only goes so far.
It did point at something. The nesting rule belongs to the DOM, and a form's state doesn't have to live there. If the tree lives in JavaScript, the DOM still decides which elements are on screen, but it no longer decides which parts of the form can submit.
That idea is what became FormTree, a headless form library for Vue, React and plain TypeScript. In FormTree, a form is a tree of definitions. A definition describes one part, like a step, a session or a single field, with its schema, its rules and its children. It holds no state, so it can be used anywhere. The form turns the tree into one state, and every part of it validates and submits the way the whole form does.
That's also what got me out of paths. A part is a node you hold, not a string you build. Components find it by its definition, and a row keeps its key when the list around it changes.
The Workshop in FormTree
Every part of the workshop becomes a definition that carries its own rules, and each workaround from before has a direct counterpart.
The Steps
A step is a definition, and the wizard is just its parent. Every part of the tree has its own submit. Next submits the step, and Publish submits the root:
const details = form.group('details')
const next = details.handleSubmit(() => goTo('schedule'))
const publish = form.handleSubmit(api.publishWorkshop)Only the current step is on screen, as a regular <form> with the step's id, and the footer button submits it with the form attribute from earlier:
<template>
<form :id="details.id" novalidate @submit.prevent="next">…</form>
<footer>
<button type="submit" :form="details.id">Next</button>
</footer>
</template>Next checks only details and never complains about a step the user hasn't reached. Both steps write into the same state, so there's no separate form state to copy into anymore. By the end the root holds everything, and Publish checks the whole tree. Mounting and unmounting don't touch that state, so a step that leaves the screen keeps its values without being told to.
One Session
A session is a node of the same tree, so it has a handleSubmit of its own, and the composable from earlier comes down to this:
const save = session.handleSubmit(async values => {
session.reset({ value: await api.saveSession(values) })
})The submit validates only that session and hands over its parsed values, so there's no path to build, no field to forget and no second look at the draft. Any other list gets the same submit without writing anything new.
The session isn't its path either. It has a key that stays with it, so its errors and touched fields go wherever it goes:
const session = sessions.items[2]
sessions.remove(0)
session.index // 1, still the same session, errors and allThe rule against two sessions on one date sits on the list, and it still applies when a single session is saved:
const sessionGroup = defineGroup({
schema: z.object({
id: z.string().optional(),
date: z.iso.date({ error: 'Pick a date' }),
seats: z.number().int().positive({ error: 'Offer at least one seat' }),
}),
})
const sessionsArray = arrayOf(sessionGroup, {
validate: sessions =>
sessions.flatMap((session, index) => {
const first = sessions.findIndex(other => other.date == session.date)
const repeated = session.date != undefined && first != index
return repeated ? [{ path: `${index}.date`, code: 'Another session is on this date' }] : []
}),
})The Venue
The venue becomes a part of its own, and format switches it on:
const venueGroup = defineGroup({
schema: z.object({
street: z.string().trim().min(1, { error: 'Enter a street' }),
city: z.string().trim().min(1, { error: 'Enter a city' }),
}),
})
const detailsGroup = defineGroup({
schema: z.object({
title: z.string().trim().min(1, { error: 'Give it a title' }),
format: z.enum(['online', 'in-person'], { error: 'Choose a format' }),
}),
children: { url: urlField, venue: venueGroup },
activeWhen: {
venue: ({ value }) => value.format == 'in-person',
},
})While the workshop is online, venue isn't checked or sent, and what the user typed is still there if they switch back. Its rules belong to venue, so its errors show up with the rest of the step instead of last.
The Seat Limit
The schedule says it needs a seat limit, the root hands it down, and the form takes the value from the plan:
interface PlanDeps {
readonly seatLimit: number
}
const scheduleGroup = defineGroupWithDeps<PlanDeps>()({
children: { sessions: sessionsArray },
validate: ({ value, deps }) => {
const seats = value.sessions.reduce((sum, session) => sum + (session.seats ?? 0), 0)
const message = `Your plan allows ${deps.seatLimit} seats`
return seats > deps.seatLimit ? { path: 'sessions', code: message } : undefined
},
})
const workshopForm = defineGroupWithDeps<PlanDeps>()({
children: { details: detailsGroup, schedule: scheduleGroup },
childDeps: {
schedule: ({ deps }) => deps,
},
})
const plan = usePlanStore()
const form = useForm(workshopForm, {
deps: () => ({ seatLimit: plan.seatLimit }),
})The form hears about the plan through deps. When the organizer upgrades, the rule is rebuilt and sessions is checked again right away, without a watcher.
The URL
The server check finally gets a place of its own, in the definition of url:
const urlField = defineField({
schema: z.string().trim().toLowerCase().min(1, { error: 'Pick a URL' }),
validateAsync: {
debounceMs: 400,
run: async (url, { signal }) => {
const taken = await api.isUrlTaken(url, signal)
return taken ? { code: 'This URL is taken' } : undefined
},
},
})It runs once the schema has passed, so it checks the same trimmed, lowercased value the submit sends, and a trailing space has nothing left to break. It's debounced and cancelled when the value changes, no other validation can wipe its error, and a submit that includes url waits for the answer.
At every level, it's the same call:
form.handleSubmit(api.publishWorkshop)
form.group('details').handleSubmit(goToSchedule)
form.group('schedule').array('sessions').items[1].handleSubmit(api.saveSession)Templates Only Bind
The binding is the part I kept from vee-validate. The rules stay in the definitions, so the template has nothing to decide. An input asks for its field by name and gets back a model and the attributes it needs, like its id, name and aria state.
<input v-model="field.model" v-bind="field.attrs" />Labels, error messages and focusing the first error go through those ids. The components stay yours, and the form never renders anything. A text field from your own design system ends up looking something like this:
<script setup lang="ts">
import { useField } from '@formtree/vue'
const props = defineProps<{ name: string; label: string }>()
const field = useField<string>(() => props.name)
</script>
<template>
<label :for="field.id">{{ label }}</label>
<input v-model="field.model" v-bind="field.attrs" />
<p :id="field.errorId">{{ field.errorMessage }}</p>
</template>Put together, the whole wizard is the definitions and a few small components, and none of them passes a node through props. The wizard creates the form and provides it. Each step finds its part by definition and provides that in turn, so its inputs bind by names relative to the step.
import { arrayOf, defineField, defineGroup, defineGroupWithDeps } from '@formtree/vue'
import { z } from 'zod'
import { api } from '../api'
interface PlanDeps {
readonly seatLimit: number
}
const urlField = defineField({
schema: z.string().trim().toLowerCase().min(1, { error: 'Pick a URL' }),
validateAsync: {
debounceMs: 400,
run: async (url, { signal }) => {
const taken = await api.isUrlTaken(url, signal)
return taken ? { code: 'This URL is taken' } : undefined
},
},
})
const venueGroup = defineGroup({
schema: z.object({
street: z.string().trim().min(1, { error: 'Enter a street' }),
city: z.string().trim().min(1, { error: 'Enter a city' }),
}),
})
const detailsGroup = defineGroup({
schema: z.object({
title: z.string().trim().min(1, { error: 'Give it a title' }),
format: z.enum(['online', 'in-person'], { error: 'Choose a format' }),
}),
children: { url: urlField, venue: venueGroup },
activeWhen: {
venue: ({ value }) => value.format == 'in-person',
},
})
const sessionGroup = defineGroup({
schema: z.object({
id: z.string().optional(),
date: z.iso.date({ error: 'Pick a date' }),
seats: z.number().int().positive({ error: 'Offer at least one seat' }),
}),
})
const sessionsArray = arrayOf(sessionGroup, {
validate: sessions =>
sessions.flatMap((session, index) => {
const first = sessions.findIndex(other => other.date == session.date)
const repeated = session.date != undefined && first != index
return repeated ? [{ path: `${index}.date`, code: 'Another session is on this date' }] : []
}),
})
export const scheduleGroup = defineGroupWithDeps<PlanDeps>()({
children: { sessions: sessionsArray },
validate: ({ value, deps }) => {
const seats = value.sessions.reduce((sum, session) => sum + (session.seats ?? 0), 0)
const message = `Your plan allows ${deps.seatLimit} seats`
return seats > deps.seatLimit ? { path: 'sessions', code: message } : undefined
},
})
export const workshopForm = defineGroupWithDeps<PlanDeps>()({
children: { details: detailsGroup, schedule: scheduleGroup },
childDeps: {
schedule: ({ deps }) => deps,
},
})<script setup lang="ts">
import { provideFormNode, useForm } from '@formtree/vue'
import { ref } from 'vue'
import { api } from './api'
import DetailsStep from './details-step.vue'
import { workshopForm } from './forms/workshop'
import ScheduleStep from './schedule-step.vue'
import { usePlanStore } from './stores/plan'
const plan = usePlanStore()
const form = useForm(workshopForm, {
deps: () => ({ seatLimit: plan.seatLimit }),
})
provideFormNode(form)
const step = ref<'details' | 'schedule'>('details')
const publish = form.handleSubmit(api.publishWorkshop)
</script>
<template>
<DetailsStep v-if="step == 'details'" @next="step = 'schedule'" />
<ScheduleStep v-else @next="publish" />
<footer>
<button type="submit" :form="form.group(step).id">
{{ step == 'details' ? 'Next' : 'Publish' }}
</button>
</footer>
</template><script setup lang="ts">
import { provideFormNode, useFormNode } from '@formtree/vue'
import { workshopForm } from './forms/workshop'
import SelectField from './select-field.vue'
import TextField from './text-field.vue'
const emit = defineEmits<{ next: [] }>()
const details = provideFormNode(useFormNode(workshopForm).group('details'))
const next = details.handleSubmit(() => emit('next'))
</script>
<template>
<form :id="details.id" novalidate @submit.prevent="next">
<TextField name="title" label="Title" />
<TextField name="url" label="URL" />
<p v-if="details.field('url').state.requesting">Checking the URL…</p>
<SelectField name="format" label="Format" :options="['online', 'in-person']" />
<fieldset v-if="details.group('venue').state.active">
<TextField name="venue.street" label="Street" />
<TextField name="venue.city" label="City" />
</fieldset>
</form>
</template><script setup lang="ts">
import { provideFormNode, useFormNode } from '@formtree/vue'
import { workshopForm } from './forms/workshop'
import SessionRow from './session-row.vue'
const emit = defineEmits<{ next: [] }>()
const schedule = provideFormNode(useFormNode(workshopForm).group('schedule'))
const sessions = schedule.array('sessions')
const next = schedule.handleSubmit(() => emit('next'))
</script>
<template>
<form :id="schedule.id" novalidate @submit.prevent="next">
<SessionRow v-for="session in sessions.items" :key="session.key" :index="session.index" />
<p>{{ sessions.errorMessage }}</p>
<button type="button" @click="sessions.push({})">Add a session</button>
</form>
</template><script setup lang="ts">
import { provideFormNode, useFormNode } from '@formtree/vue'
import { scheduleGroup } from './forms/workshop'
import NumberField from './number-field.vue'
import TextField from './text-field.vue'
const props = defineProps<{ index: number }>()
const sessions = useFormNode(scheduleGroup).array('sessions')
const session = provideFormNode(sessions.items[props.index])
</script>
<template>
<TextField name="date" label="Date" />
<NumberField name="seats" label="Seats" />
<button type="button" @click="sessions.remove(session.index)">Remove</button>
</template>Trying It
Trying it doesn't mean switching libraries. Any definition can be the root of its own form, and the Vue and React adapters need no app-wide setup, so FormTree can start in one component next to whatever you use today:
pnpm add @formtree/vuePick the form that keeps collecting workarounds, like a wizard or a list saved row by row. A login form won't change much, and that's fine, because your current library is great at those.
We run FormTree in production, well past the experiment it started as. The docs have live examples and tutorials, and if something feels off or missing, I'd love to hear about it on GitHub.
The forms didn't get any simpler, and they were never going to. The rules are all still there. They just live with the parts they belong to now, and every part of a form gets to be a form. 🌳