@k8ordo/form

A React form library that derives HTML constraint attributes and server-side validation from a zod schema

bash
npm install @k8ordo/form zod
schema.ts
export const talkSchema = z.object({
  title: z.string().min(1).max(120),
});
talk-form.tsx
const title = form.field('title');

<input {...title.input} />
HTML
<input name="title" type="text" required
  minlength="1" maxlength="120">

Constraints written once, in the schema

From the schema, formFields derives the input attributes (such as required and maxlength) and zod’s error messages.

parseForm checks the submitted FormData against the same schema. No constraint is copied into JSX or the server.

page.tsx
const fields = formFields(talkSchema);

fields.fields.title.input;
// { name: 'title', type: 'text', required: true,
//   minLength: 1, maxLength: 120 }

fields.fields.title.messages.tooLong;
// 'Too big: expected string to have <=120 characters'

Validation before JavaScript loads

The constraints are attributes in the server-rendered HTML, so the browser checks the input before the page finishes loading.

Once the page has loaded, leaving a field and submitting both run the same schema check and show zod’s error messages. Values are not kept in React state, so typing does not re-render on every keystroke.

Playground

Filter form demo

A GET form derived from a schema; submitting it rewrites this page’s URL.

URL
No query (all defaults)
state
{ q: '', min: 0, inStock: false }

Try it

  1. Type -1 into “Minimum” and leave the field. zod’s error message appears.
  2. Press “Filter” anyway. The submission stops, and focus returns to that field.
  3. Submit valid values. The URL and the state below it show the same values.

Server errors shown on their fields

parseForm returns each failure keyed by its field, together with the submitted values.

useForm shows each error on its field and moves focus to the first field that failed. What was typed stays, ready to be fixed and sent again.

actions.ts
export async function createTalk(
  _prev: FormState,
  formData: FormData,
) {
  const parsed = parseForm(talkSchema, formData);
  if (!parsed.success) return parsed.state;

  await insertTalk(parsed.data);
  redirect(href('/talks'));
}