@k8ordo/form

Field types

The schema type decides which control a field becomes. For each type, you can write the schema and pass input to the control.

On this page

Schema to control

ts
z.string()                        → type="text"
z.email() / z.url()               → type="email" / type="url"
z.iso.date() / z.iso.time()       → type="date" / type="time"
z.iso.datetime({ local: true })   → type="datetime-local"
z.coerce.number()                 → type="number"
z.boolean() / z.literal(true)     → type="checkbox"
z.stringbool()                    → type="checkbox" value="true"
z.file()                          → type="file"
z.enum([…])                       → <select>
z.array(z.enum([…]))              → type="checkbox"
z.uuid()                          → type="text"

The input that field() returns carries the attributes for the schema. Most of the time you spread it onto the control as it is. Radio buttons and several options take only part of it, as their sections below show.

The input for z.enum() and z.array(z.enum()) has no type. Spread the first onto a <select>, and render the second as one checkbox per option. Any type not listed here (z.uuid() and so on) becomes a text field.

Text

ts
z.object({
  handle: z.string().min(3).max(20).regex(/^[a-z0-9_]+$/),
});

// handle.input
// { name: 'handle', type: 'text', required: true,
//   minLength: 3, maxLength: 20, pattern: '^[a-z0-9_]+$' }

z.string() becomes a text field. .min() becomes minlength, .max() becomes maxlength, and .regex() becomes pattern.

z.email() becomes type="email" and z.url() becomes type="url". The browser checks the format.

Warning

Pitfall

An empty text field submits "". Even with .optional(), a field with .min(1) does not accept a blank.

To allow a blank, write a schema that accepts "".

ts
bio: z.string().min(1).optional(),
bio: z.string().max(200),

Dates and times

ts
z.object({
  day: z.iso.date(),
  start: z.iso.time(),
  doors: z.iso.datetime({ local: true }),
});

The z.iso formats become the browser’s date and time controls. The value arrives as an ISO string.

To receive a Date, use z.coerce.date(). It becomes a text field. z.date() accepts no string, so formFields throws (フォームが送信できる値がありません).

Numbers

ts
z.object({
  seats: z.coerce.number().int().min(1).max(500),
  price: z.coerce.number().multipleOf(0.01).optional(),
});

// seats.input → { type: 'number', required: true, step: 1, min: 1, max: 500 }
// price.input → { type: 'number', step: 0.01 }

Write a numeric field with z.coerce.number(). It becomes type="number", and .min() and .max() become min and max.

step is 1 after .int() and the given value after .multipleOf(). Without either it is any, which allows decimals.

An empty numeric field submits nothing, and is not 0. Add .optional() to allow a blank.

Warning

Pitfall

z.number() does not work. Every submitted value is a string, so no input would pass. formFields throws (z.coerce.number() を使ってください).

One of several options

tsx
const format = form.field('format');

<select {...format.input}>
  <option value="">Choose a format</option>
  <option value="talk">Talk</option>
  <option value="workshop">Workshop</option>
</select>

Spread a z.enum() field’s input onto a <select>. With an empty-valued option first, required means “choose one”.

With .optional(), the empty option can be submitted as it is.

Radio buttons

tsx
const format = form.field('format');

{['talk', 'workshop'].map((option) => (
  <label key={option}>
    <input
      defaultChecked={state.values?.format === option}
      name={format.input.name}
      required={format.input.required}
      type="radio"
      value={option}
    />
    {option}
  </label>
))}

Give a radio button the name and required from input. Restore the previous choice per option with defaultChecked from state.values.

@k8ordo/ui’s Radio and RadioCard take the spread input as it is. See Forms.

Warning

Pitfall

Do not spread input onto a radio button as it is. After a submission, input carries the previous choice as defaultValue, which collides with each radio button’s value.

Checkbox

ts
z.object({
  newsletter: z.boolean(),
  terms: z.literal(true, 'Agree to the terms to continue'),
});

z.boolean() becomes a checkbox. An unchecked box arrives as false, so the field is never required.

When the box must be checked, as with agreeing to terms, use z.literal(true).

Checkbox that submits a string

ts
z.object({
  inStock: z.stringbool().default(false),
});

// inStock.input → { name: 'inStock', type: 'checkbox', value: 'true' }

A z.stringbool() checkbox submits the string in input.value when checked, "true" by default. Use it in a GET form whose values stay in the URL.

An unchecked box submits nothing, so add .default(false) or .optional(). formFields throws on .default(true) (false を送れません).

Several options

tsx
const tags = form.field('tags');
const checked = state.values?.tags;

{['react', 'css', 'a11y'].map((option) => (
  <label key={option}>
    <input
      defaultChecked={Array.isArray(checked) && checked.includes(option)}
      name={tags.input.name}
      type="checkbox"
      value={option}
    />
    {option}
  </label>
))}

z.array(z.enum()) becomes a group of checkboxes sharing one name. The checked values arrive as an array, and none checked is [].

A lower bound such as .min(2) has no HTML attribute, so the browser does not check it. To check it in the browser too, declare the minChecked rule on Cross-field rules.

Files

ts
z.object({
  slides: z.file().mime(['application/pdf']).max(10_000_000),
});

// slides.input → { name: 'slides', type: 'file', required: true,
//                  accept: 'application/pdf' }

z.file() becomes a file control, and .mime() becomes accept.

accept only narrows what the file picker offers. The browser never checks the type, so type and size are checked on the server alone.

After a failed submission, the chosen file does not come back: no browser lets a value be put into a file control.

Passwords

ts
password: z.string().min(8).meta({ input: 'password' }),

Mark a field with input: "password" in its metadata, and it becomes a type="password" field.

After a failed submission, what was typed is left out of state.values.

Information

Note

zod/mini has no .meta(); add it with .check(z.meta(…)).

ts
password: z.string().check(z.minLength(8), z.meta({ input: 'password' })),
k8ordo

React libraries that use Baseline features without holding back.