@k8ordo/form

Nested and repeated rows

Work with an object inside the schema through a field() path, and with an array of objects through the rows of array(). In both cases the path is the name the browser submits.

On this page

Nested objects

schema.ts
z.object({
  user: z.object({
    email: z.email(),
  }),
});
profile-form.tsx
const email = form.field('user.email');

<input {...email.input} />

Pass field() a dotted path. The submitted name and the key in state.errors are that same path.

An object behind .optional() or .default() keeps its fields, and they are used the same way.

Warning

Pitfall

Render the fields even when the object may be left out. When a name is missing from the FormData, parseForm throws スキーマにあるフィールドが送信されていません.

Repeated rows

schema.ts
z.object({
  items: z
    .array(
      z.object({
        name: z.string().min(1),
        quantity: z.coerce.number().int().min(1),
      }),
    )
    .min(1)
    .max(3),
});
order-form.tsx
const items = form.array('items');

{items.rows.map((row) => (
  <fieldset key={row.key}>
The `key` that tells rows apart
    <input {...row.field('name').input} />
    <input {...row.field('quantity').input} />
    {items.canRemove && (
      <button onClick={row.remove} type="button">
        Remove
      </button>
    )}
  </fieldset>
))}
{items.canAdd && (
  <button onClick={items.add} type="button">
    Add a row
  </button>
)}

Use array() for an array of objects. Get each row’s fields with row.field(), and pass row.key to key.

canAdd turns false once the row count reaches the schema’s .max(), and canRemove once it reaches .min(). The buttons only allow counts the server accepts.

Per row, React state keeps only the key. Adding or removing a row never puts the typed values into state.

Playground

Order rows demo

An order form that takes one to three rows and lists the submitted names and values.

Row 1

Try it

  1. Press “Add a row” twice. The button disappears at the third row: that is the schema’s .max(3).
  2. Leave the second row empty and press “Submit”. The submission stops and focus moves to the second row.
  3. Remove the first row, fill the rest, and submit. The indexes close up, starting again at items[0].name.

Row count errors

order-form.tsx
<form {...form.props} action={formAction}>
  {items.error !== undefined && (
    <p {...items.errorProps}>{items.error}</p>
  )}
  {items.rows.map((row) => (
    <fieldset key={row.key}>{/* fields */}</fieldset>
  ))}
</form>

An error for too few or too many rows belongs to no row. It is set on items.error.

Spread items.errorProps onto the element that shows it. Without them, when only the row count stops a submission, focus moves nowhere. A screen reader announces nothing either.

Show the error above the rows. When a row has errors too, focus lands here first, and Tab moves on into the rows.

Submitted names

ts
row.field('name').input.name;
// 'items[0].name'

state.errors;
// { 'items[1].quantity': 'Order at least one' }

A field inside a row is named with its index, as in items[0].name. The key in state.errors has the same shape.

Removing a row moves the later rows up one index. Errors from validation in the browser move with them.

Warning

Pitfall

Errors the server returned are not renumbered. Remove a row above one, and an error not yet fixed shows on whichever row now has that index.

Initial row count

Before any submission, the form renders the schema’s .min() rows, or none without one.

After a submission, it renders the count parseForm returns in state.rows. A retry without JavaScript keeps the same rows.

The count is read from the submitted indexes and capped at .max(). A forged large index cannot make the server allocate a large array.

Arrays of strings

tags-form.tsx
const tags = form.array('tags');

{tags.rows.map((row) => (
  <input key={row.key} {...row.field().input} />
))}

In an array of plain values such as z.array(z.string()), a row has no field name of its own. Call row.field() with no argument, and its name is tags[0].

Information

Note

An array of enums (z.array(z.enum([…]))) does not become rows. It is a checkbox group, handled as one field. See Field types.

Unsupported shapes

A repeat inside a repeat passes type checking. At runtime formFields and parseForm throw 繰り返しの中の繰り返しは name の添字が一意に決まらないため表現できません.

Rules such as sameAs cannot name a field inside a row. Write a row field’s checks in the schema.

k8ordo

React libraries that use Baseline features without holding back.