Skip to content
Suriyaprakash.
Engineering

Field note / Engineering+

SchemaForm: Build React Forms from a Zod Schema, with Layout, Conditions, and Guards

Build React forms from one Zod schema, with column and row spans, sections, conditional fields, slots, and submission guards.

Published
Reading time17 min read
Filed underEngineering

Most forms are the same shape: a few inputs, some rules, error messages under the fields, and a submit button. The repetitive part is where drift creeps in. One form shows errors on blur, another only after submit, and the messages disagree with the server.

SchemaForm takes the repetition out. You describe the fields and their rules once, as a Zod schema, and the component renders the inputs, labels, layout, validation messages, and submit handling from that description. This post shows how to use it end to end: the basic form, layout with column spans, row spans, sections and groups, conditional fields, cross-field rules, and the extension points for custom content and submission guards. It ends with the limits you should know before you adopt it.

The examples assume you know React and basic Zod. SchemaForm is a component built for this site, so the code here is the code the site runs. To see the layout controls working, open the SchemaForm builder. You can arrange sections and groups, set column and row spans, preview the form live, and view the Zod schema it generates. The builder does not show slots, guards, or the other extension points below, so those are code-only.

Quick answer

  • One schema defines the form. Field types, labels, validation, and layout come from the same Zod object.
  • Layout is declared per field. colSpan, rowSpan, section, and group are metadata on each field, and the component builds the grid.
  • Conditions and cross-field rules have separate homes. visibleWhen decides whether a field shows. superRefine decides whether a value is valid.
  • Extension points are narrow. Slots add content under a field. Guards block a submit. children, renderActions, hideActions, and formKey cover the rest.
  • The schema is the only validator. The form turns off the browser's built-in checks, so your messages are the ones the user sees.

Your first form

import { z } from "zod";
import { SchemaForm } from "@/components/form/SchemaForm";

const contactSchema = z.object({
  name: z.string().min(2, "Name must be at least 2 characters"),
  email: z.string().email("Enter a valid email"),
  message: z.string().min(10, "Message must be at least 10 characters"),
});

export function ContactForm() {
  return (
    <SchemaForm
      schema={contactSchema}
      defaultValues={{ name: "", email: "", message: "" }}
      submitLabel="Send"
      onSubmit={async (values) => {
        await sendMessage(values);
      }}
    />
  );
}

You do not write any markup. The component reads the schema and decides the field types from the Zod types:

Zod typeField rendered
z.string()Text input
z.string().email()Email input
z.number()Number input
z.boolean()Switch
z.enum([...])Select, with one option per value
z.date()Date field
z.array(z.object({...}))Array of items

Labels come from the field name, so firstName becomes "First name". To change a label, a placeholder, or the help text, attach metadata to the field with fieldMeta:

import { fieldMeta } from "@/components/form/fieldMeta";

const profile = z.object({
  displayName: z
    .string()
    .min(2, "Use at least 2 characters")
    .describe(fieldMeta({ label: "Display name", placeholder: "How others see you" })),
});

fieldMeta stores the metadata as a JSON string in the schema's description, and the parser reads it back. It is a small convention, and it is the same channel used for layout and conditions below.

Layout: column spans, row spans, sections, and groups

Column spans

By default each field takes the full width of the form. Set colSpan to put fields side by side:

const address = z.object({
  city: z.string().describe(fieldMeta({ label: "City", colSpan: 6, order: 1 })),
  postcode: z.string().describe(fieldMeta({ label: "Postcode", colSpan: 6, order: 2 })),
});

A colSpan of 6 gives the field a cell of col-span-12 md:col-span-6. On a phone it takes the full width, and from the md breakpoint up it takes six of the twelve grid columns. Two fields with colSpan: 6 sit side by side, and a third one wraps to the next row.

Row spans

rowSpan makes a field's cell span more than one grid row:

const notes = z.object({
  summary: z.string().describe(fieldMeta({ label: "Summary", colSpan: 6, rowSpan: 2, order: 1 })),
});

A rowSpan of 2 adds the row-span-2 class to the cell, so it takes two rows of the grid. The rendered height depends on the cells around it, so check the look in a browser before you rely on it.

Sections and groups

For larger forms, group fields under a titled section, and optionally put related fields in a group inside it:

const account = z.object({
  firstName: z.string().describe(
    fieldMeta({
      label: "First name",
      section: "account",
      sectionTitle: "Account",
      group: "identity",
      groupTitle: "Identity",
      colSpan: 6,
      order: 1,
    }),
  ),
  lastName: z.string().describe(
    fieldMeta({
      label: "Last name",
      section: "account",
      sectionTitle: "Account",
      group: "identity",
      groupTitle: "Identity",
      colSpan: 6,
      order: 2,
    }),
  ),
  bio: z.string().describe(
    fieldMeta({
      label: "Bio",
      section: "profile",
      sectionTitle: "Profile",
      sectionDescription: "Public details",
      colSpan: 12,
      rowSpan: 2,
      order: 3,
    }),
  ),
});

The form renders two sections, "Account" and "Profile". Account holds an "Identity" group with the two name fields side by side. Profile has a description under its title and a tall bio field.

Some rules govern the layout:

  • The structured layout turns on only when a field declares a section or a group. A schema with neither renders as one flat grid, with no headings.
  • Sections are ordered by sectionOrder, not by where they are declared. Fields inside a section are ordered by order. For example, a section with sectionOrder: 1 renders before one with sectionOrder: 2, whatever order they are declared in.
  • Give every field in a structured form a section. A field without one has no heading, and it is placed by its order alongside the sections. That is easy to miss when a form grows.

The visual result is a bordered section shell with a heading and description, and inside it a dashed group box with its own heading, and then the grid of fields.

Conditional fields

A field can be shown only when another field has a particular value:

import { fieldMeta, when } from "@/components/form/fieldMeta";

const signUp = z.object({
  plan: z.enum(["free", "pro"]),
  company: z
    .string()
    .optional()
    .describe(fieldMeta({ label: "Company", visibleWhen: when.equals("plan", "pro") })),
});

when has six operators: equals, notEquals, contains, notContains, greaterThan, and lessThan. A field can also take an array of conditions, and then every condition must hold.

Visibility and validity are separate. The visibleWhen metadata decides whether the company input appears. It does not make the field required. Make the field optional in the schema, and enforce the rule in a cross-field check when the condition holds:

const signUp = z
  .object({
    plan: z.enum(["free", "pro"]),
    company: z
      .string()
      .optional()
      .describe(fieldMeta({ label: "Company", visibleWhen: when.equals("plan", "pro") })),
  })
  .superRefine((values, ctx) => {
    if (values.plan === "pro" && !(values.company ?? "").trim()) {
      ctx.addIssue({ code: "custom", path: ["company"], message: "Company is required for Pro" });
    }
  });

The path ["company"] puts the message under the company field. The split is deliberate: a hidden field's rules still run, so the field stays optional in the schema, and the required rule applies only when the plan is Pro.

Cross-field rules

Any rule that involves more than one field goes in superRefine, with a path that names the field that should show the error:

const passwordChange = z
  .object({
    password: z.string().min(12, "Use at least 12 characters"),
    confirm: z.string(),
  })
  .superRefine((values, ctx) => {
    if (values.password !== values.confirm) {
      ctx.addIssue({ code: "custom", path: ["confirm"], message: "Passwords do not match" });
    }
  });

A message with a path shows under that field. A message with no path does not show under any field, so always set one.

Extension points

Schemas describe most forms. The rest of the work happens at a few named points.

Field slots

A slot adds content inside one field's cell, after its errors. It receives the form instance, the current values, and the field's value and handleChange:

<SchemaForm
  schema={signUp}
  defaultValues={{ plan: "free", company: "" }}
  fieldSlots={{
    company: () => (
      <p className="text-sm text-muted-foreground">
        Company names appear on invoices. You can change this later.
      </p>
    ),
    plan: ({ values, field }) => (
      <button type="button" onClick={() => field.handleChange("pro")}>
        Upgrade to Pro{values.plan === "pro" ? " (current)" : ""}
      </button>
    ),
  }}
/>

A slot can write its own field through handleChange. It cannot replace the input. Use a slot for hints, previews, and actions that belong next to a field.

Submission guards

A guard runs before onSubmit, after the schema has passed. It returns null to let the submit through, or a message to block it:

import * as React from "react";
import type { FormInstance } from "@/components/form/types";

function TermsForm({ accepted, onSubmit }: { accepted: boolean; onSubmit: (v: unknown) => void }) {
  const formRef = React.useRef<FormInstance>(null);

  React.useEffect(() => {
    return formRef.current?.registerGuard("terms", () =>
      accepted ? null : "Please accept the terms first",
    );
  }, [accepted]);

  return <SchemaForm formRef={formRef} schema={signUp} onSubmit={onSubmit} />;
}

The message appears at the top of the form, not under a field, because a guard is not tied to one field. Several guards can be registered. They run in order, and the first message stops the submit. Registering in an effect and returning the unregister function keeps the guard in step with the component.

Children, custom actions, and hiding the actions row

  • children render between the fields and the actions. Use them for a notice, a summary, or a consent checkbox that is not part of the schema.
  • renderActions replaces the default Cancel, Reset, and Submit row. It receives the form handle, canSubmit, isSubmitting, and the onCancel and onReset you passed in.
  • hideActions removes the built-in row entirely. Use it in a wizard that brings its own navigation.

Resetting with formKey

formKey resets the form to defaultValues when its value changes. The form is not remounted, and it is not reset on the first render or when the key stays the same. Use it to reuse one form for several records: change the key when the record changes.

The form handle

formRef gives you a handle with reset({ values }), handleSubmit(), setFieldValue(name, value), state, and registerGuard. The reset call takes an object with a values key, which matches the type.

Validation behaviour

Errors show after a field is touched or after the form is submitted. Before either happens, a field stays quiet, so a user is not greeted with errors on an empty form.

The form also sets noValidate on the <form> element, and the reason matters. An email input with type="email" runs a browser check before any JavaScript. If the value fails that check, the browser blocks the submit and shows its own bubble, and your schema never runs. The user sees neither your message for that field nor the messages for the others. With noValidate set, the schema is the only validator, and every message comes from it. The cost is that browser-only checks, such as a pattern attribute, stop applying, so put those rules in the schema.

Standalone form or SchemaForm?

The same sign-up form, written both ways. It has a name, an email, a password, a plan, and a company field that appears only for the Pro plan. Both versions show the same messages for the same invalid input.

Written by hand

This version uses plain React state. The rules are a function, and the markup is explicit.

import * as React from "react";

type Values = {
  name: string;
  email: string;
  password: string;
  plan: "free" | "pro";
  company: string;
};
type Errors = Partial<Record<keyof Values, string>>;

function validateByHand(v: Values): Errors {
  const e: Errors = {};
  if (v.name.length < 2) e.name = "Name must be at least 2 characters";
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.email)) e.email = "Enter a valid email";
  if (v.password.length < 12) e.password = "Password must be at least 12 characters";
  if (v.plan === "pro" && !v.company.trim()) e.company = "Company is required for Pro";
  return e;
}

function HandWrittenSignUp({ initial, onValid }: { initial: Values; onValid: (v: Values) => void }) {
  const [values, setValues] = React.useState(initial);
  const [submitted, setSubmitted] = React.useState(false);
  const errors = validateByHand(values);
  const shown = (key: keyof Values) => (submitted ? errors[key] : undefined);

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        setSubmitted(true);
        if (Object.keys(validateByHand(values)).length === 0) onValid(values);
      }}
    >
      <label htmlFor="hw-name">Name</label>
      <input id="hw-name" value={values.name} onChange={(e) => setValues({ ...values, name: e.target.value })} />
      {shown("name") && <p>{shown("name")}</p>}

      <label htmlFor="hw-email">Email</label>
      <input id="hw-email" value={values.email} onChange={(e) => setValues({ ...values, email: e.target.value })} />
      {shown("email") && <p>{shown("email")}</p>}

      <label htmlFor="hw-password">Password</label>
      <input id="hw-password" value={values.password} onChange={(e) => setValues({ ...values, password: e.target.value })} />
      {shown("password") && <p>{shown("password")}</p>}

      <label htmlFor="hw-plan">Plan</label>
      <select id="hw-plan" value={values.plan} onChange={(e) => setValues({ ...values, plan: e.target.value as "free" | "pro" })}>
        <option value="free">Free</option>
        <option value="pro">Pro</option>
      </select>

      {values.plan === "pro" && (
        <>
          <label htmlFor="hw-company">Company</label>
          <input id="hw-company" value={values.company} onChange={(e) => setValues({ ...values, company: e.target.value })} />
          {shown("company") && <p>{shown("company")}</p>}
        </>
      )}

      <button type="submit">Create account</button>
    </form>
  );
}

That is about 57 lines, and the rules, labels, inputs, and error lines are all written out. Nothing here is hidden or inferred, and you can read the whole form in one place.

With SchemaForm

The same rules, written once as a schema, and one component call:

import { z } from "zod";
import { fieldMeta, when } from "@/components/form/fieldMeta";
import { SchemaForm } from "@/components/form/SchemaForm";

const signUpSchema = z
  .object({
    name: z.string().min(2, "Name must be at least 2 characters"),
    email: z.string().email("Enter a valid email"),
    password: z.string().min(12, "Password must be at least 12 characters"),
    plan: z.enum(["free", "pro"]),
    company: z
      .string()
      .optional()
      .describe(fieldMeta({ label: "Company", visibleWhen: when.equals("plan", "pro") })),
  })
  .superRefine((v, ctx) => {
    if (v.plan === "pro" && !(v.company ?? "").trim()) {
      ctx.addIssue({ code: "custom", path: ["company"], message: "Company is required for Pro" });
    }
  });

<SchemaForm
  schema={signUpSchema}
  defaultValues={{ name: "", email: "", password: "", plan: "free" }}
  submitLabel="Create account"
  onSubmit={createAccount}
/>

The schema is 16 lines. The labels, inputs, select options, and error lines come from it. The company field's visibility comes from visibleWhen, and its required rule comes from the superRefine.

Side by side

ConcernWritten by handWith SchemaForm
Size of this formAbout 57 lines16 lines of schema, plus one component call
Where rules liveOne validation functionThe Zod schema; cross-field rules in superRefine
Labels and inputsWritten for each fieldInferred from field names and Zod types
Conditional fieldAn if in the JSXvisibleWhen, plus a matching rule in the schema
When errors showAfter submit, in this versionAfter a field is touched, or after submit
LayoutWhatever markup you writecolSpan, rowSpan, sections, and groups
Browser validationOff here, since the inputs have no type checksOff by design (noValidate), so the schema decides
Extra content under a fieldAny JSXA field slot, which adds content but cannot replace the input
Blocking a submitA check in your submit handlerA submission guard, shown at the top of the form
Adding a fieldInput, label, handler, and error lineOne schema line, plus metadata if it needs layout or a condition
What you must learnNothing beyond ReactThe metadata conventions, error paths, and visibility rules

What the hand-written version does better

It accepts any widget, because the markup is yours. It has no conventions to learn, so a new team member can read the whole form and understand it. It also lets you show errors on whatever schedule suits the screen, without fighting a component's rules.

What SchemaForm does better

It removes the repetition. Each field's label, input, and error line comes from one definition, so the forms in an app stay consistent. Layout, conditions, guards, and slots are built in, so you do not write them for each screen. And the same schema can validate the server request, if you share it.

Which to choose

Use a standalone form for one or two screens with unusual widgets or behaviour, or where the markup must be fully custom.

Use SchemaForm when many screens share the same pattern, such as admin forms generated from data types, or when the rules already live in a Zod schema shared with the API.

Most projects end up with both. SchemaForm handles the routine screens, and a hand-written form handles the few that need something different. Decide where that line sits before you cross it, and keep the rules for each field in one place, whichever approach you pick.

Checklist

  • Put every rule in the schema, and check that each message shows under the field it belongs to.
  • Keep hidden fields optional in the schema, and enforce their rules in superRefine when the condition holds.
  • Give every field in a structured form a section, and give each section a sectionOrder if the order matters.
  • Use colSpan for side-by-side fields, and confirm rowSpan visually in a browser.
  • Use slots for hints beside a field, and guards for submit-time rules that are not tied to one field.
  • Use formKey to reuse a form for several records.
  • Test the messages, not only the rules, for every field.

FAQ

Can I use SchemaForm without sections or groups?

Yes. A schema with no section or group renders as one flat grid, with no headings. Layout is optional.

Why are my side-by-side fields stacked on a phone?

That is by design. Every field is full width below the md breakpoint, and colSpan applies from md up.

How do I show an error that involves two fields?

Use superRefine with the path of the field that should show it. If the error has no natural field, register a guard and return the message.

Does the form handle file and array fields?

Array fields are part of the parser's type list, and the form has code for them, but they are not verified here. Test them in your app before you rely on them.

Can a slot read other fields?

Yes. A slot receives the current values, so it can read any field. Use field.handleChange to change its own field. Register guards outside the render, in an effect, not inside a slot.

Why is my submit blocked when the field is hidden?

A hidden field's rule still runs. If it fails, the submit is blocked, and no message shows because the field is not on screen. Keep hidden fields optional and enforce the rule when the field is visible.

Final mental model

one Zod schema
      |
      +--> field types, labels, and options    (from Zod types and fieldMeta)
      +--> layout                              (colSpan, rowSpan, section, group, order)
      +--> visibility                          (visibleWhen, evaluated against values)
      +--> validity                            (schema rules and superRefine)
      |
      v
rendered form
      |
      +--> slots add content under a field
      +--> children sit between the fields and the actions
      +--> actions row (or renderActions, or hidden)
      |
      v
submit
      |
      +--> schema validation  --fails--> messages under fields
      +--> guards             --blocks--> message at the top
      +--> onSubmit(data)

A schema describes what a valid form looks like. Layout and visibility describe what the user sees. Slots, guards, and the handle are the points where your code takes over. Most forms need only the first two, and the rest exist for the cases where they don't.

About the author

Suriyaprakash Somu is a full-stack developer based in Erode, Tamil Nadu, building React and Node.js applications on relational databases. He works on customer-facing experiences, reusable interfaces and access-controlled backend workflows. Explore his development work or discuss a project or developer role.