Zod
You may want to use Zod validator because:
- You can use Zod schema as a source of truth for the form value type (
z.infer
). - This is an easy way to add custom error messages
Installation
Section titled “Installation”npm i @sjsf/zod4-validator zod
yarn add @sjsf/zod4-validator zod
pnpm add @sjsf/zod4-validator zod
bun add @sjsf/zod4-validator zod
Example
Section titled “Example”<script lang="ts"> import { BasicForm, createForm, ON_ARRAY_CHANGE, ON_CHANGE, ON_INPUT, } from "@sjsf/form"; import { setupFormValidator } from "@sjsf/zod4-validator/classic"; import { z } from "zod/v4"; import en from "zod/v4/locales/en.js"
import * as defaults from "@/components/form-defaults";
import { initialValue, uiSchema } from "../shared";
z.config(en())
const zodSchema = z.object({ id: z .string() .regex(new RegExp("^\\d+$"), "Must be a number") .min(8) .optional(), active: z.boolean(), skills: z.array(z.string().min(5)).min(4).optional(), multipleChoicesList: z .array(z.enum(["foo", "bar", "fuzz"])) .max(2) .optional(), });
const { schema, validator } = setupFormValidator(zodSchema, { uiSchema });
const form = createForm({ ...defaults, schema, uiSchema, validator, fieldsValidationMode: ON_INPUT | ON_CHANGE | ON_ARRAY_CHANGE, initialValue: initialValue, });</script>
<BasicForm {form} novalidate />
<pre>{JSON.stringify(form.value, null, 2)}</pre>
import type { Schema, UiSchema } from "@sjsf/form";
export const schema: Schema = { type: "object", properties: { id: { type: "string", minLength: 8, pattern: "^\\d+$", }, active: { type: "boolean", }, skills: { type: "array", minItems: 4, items: { type: "string", minLength: 5, }, }, multipleChoicesList: { type: "array", maxItems: 2, items: { type: "string", enum: ["foo", "bar", "fuzz"], }, }, },};
export const uiSchema: UiSchema = { id: { "ui:options": { title: "Identifier", }, }, active: { "ui:options": { title: "Active", }, }, multipleChoicesList: { "ui:options": { title: "Pick max two items", }, },};
export const initialValue = { id: "Invalid", skills: ["karate", "budo", "aikido"], multipleChoicesList: ["foo", "bar", "fuzz"],};
Async validation
Section titled “Async validation”This validator supports async validation.
import { setupAsyncFormValidator } from "@sjsf/zod-validator/classic";
const { schema, validator } = setupAsyncFormValidator(zodSchema);