Lesson 6 of 9 · 21m
Forms, Validation, and Async Workflows
Build Vue forms that preserve user input, validate at humane moments, and treat submit as a state machine instead of a button click.
Forms expose every weak point in state design. Lose focus and the input resets; server validation arrives late; double-submit creates two records; an error message exists visually but is invisible to assistive technology. The good news is that robust forms are mostly discipline, not cleverness.
Keep the form model explicit
<script setup lang="ts">
const form = reactive({
email: "",
password: "",
});
const errors = reactive<Record<string, string | null>>({});
const status = ref<"idle" | "submitting" | "success" | "error">("idle");
</script>Group related fields into one model when they submit together. Do not create twenty independent refs because each input happened to start life in isolation. At the same time, don't store derived validation results as a second source of truth — compute or regenerate them from the form model.
Validate schemas at boundaries
import { z } from "zod";
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(12),
});
const result = loginSchema.safeParse(form);
if (!result.success) {
errors.email = result.error.formErrors.fieldErrors.email?.[0] ?? null;
}A schema library is not about being fashionable. It creates one definition that client validation, server validation, and tests can share or mirror. Validate fields on blur once the user has interacted with them, validate everything on submit, and clear an error as soon as the field becomes valid.
Submit is a state machine
<button type="submit" :disabled="status === 'submitting'">
{{ status === "submitting" ? "Signing in…" : "Sign in" }}
</button>idle → submitting → success | error is the minimum. Disable the submitter while pending, prevent accidental double activation, preserve entered data on failure, and focus or announce errors accessibly. Never rely only on @click on the button; use a real <form @submit.prevent> so Enter key behavior and browser semantics work.
Async validators need race protection
Availability checks ("is this username taken?") are requests like any other. Debounce them, cancel stale ones, and don't mark a field invalid based on a response to an older value. This is where composables shine: a useAsyncValidator can own request generation and state transitions while the component renders the result.
Field notes
autocomplete, correct input types, and real labels are free usability. Add them before building elaborate validation UI.- File inputs are inherently uncontrolled; use refs or FormData instead of trying to bind a FileList as ordinary state.
- Server errors belong near the fields they mention when possible, not only in a toast that disappears.
- If paste handling matters — codes, payment fields, rich text — test paste explicitly. Mobile keyboards exercise paths desktop users miss.
Was this lesson helpful?