Schema#
The same sign-up form, validated by eight schema libraries. In each, the inputs hold strings and onSubmit receives the parsed output: the name trimmed, the age a number. See Schema validation.
- Zod, Valibot, ArkType, Yup (1.7+), Effect Schema implement Standard Schema: pass the schema to the
schemaprop. No resolver package;onSubmitis typed by the schema output. - Ajv (JSON Schema), Joi, Superstruct: pass a resolver from
@hookform/resolverstoformOptions.resolver.
Field rules are not used with a schema: all validation, messages included, lives in the schema. The * marker comes from rules.required, so set required: true on a field to show it.
pnpm add zod. z.coerce.number<string>() keeps the input type a string while the output is a number.
import { useState } from "react";
import { z } from "zod";
import { Form } from "../form.setup";
// The inputs hold strings; the schema trims the name and parses the age
const signupSchema = z.object({
name: z.string().trim().min(1, "Name is required"),
email: z.email("Invalid email"),
age: z.coerce.number<string>().int().min(18, "Must be 18 or older"),
});
export default function SignupForm() {
const [output, setOutput] = useState<z.output<typeof signupSchema>>();
return (
<Form
schema={signupSchema}
defaultValues={{ name: "", email: "", age: "" }}
config={{
name: { type: "text", label: "Name" },
email: { type: "text", label: "Email" },
age: { type: "text", label: "Age", props: { inputMode: "numeric" } },
}}
// `data` is the schema output: the name trimmed, the age a number
onSubmit={(data) => setOutput(data)}
>
<button type="submit">Sign up</button>
{output && <pre data-testid="output">{JSON.stringify(output)}</pre>}
</Form>
);
}
pnpm add valibot. v.toNumber() parses the age inside the pipe.
import { useState } from "react";
import * as v from "valibot";
import { Form } from "../form.setup";
// The inputs hold strings; the schema trims the name and parses the age
const signupSchema = v.object({
name: v.pipe(v.string(), v.trim(), v.minLength(1, "Name is required")),
email: v.pipe(v.string(), v.email("Invalid email")),
age: v.pipe(v.string(), v.toNumber(), v.integer(), v.minValue(18, "Must be 18 or older")),
});
export default function SignupForm() {
const [output, setOutput] = useState<v.InferOutput<typeof signupSchema>>();
return (
<Form
schema={signupSchema}
defaultValues={{ name: "", email: "", age: "" }}
config={{
name: { type: "text", label: "Name" },
email: { type: "text", label: "Email" },
age: { type: "text", label: "Age", props: { inputMode: "numeric" } },
}}
// `data` is the schema output: the name trimmed, the age a number
onSubmit={(data) => setOutput(data)}
>
<button type="submit">Sign up</button>
{output && <pre data-testid="output">{JSON.stringify(output)}</pre>}
</Form>
);
}
pnpm add arktype. Put a custom message on the type that checks the value (after a parse).
import { type } from "arktype";
import { useState } from "react";
import { Form } from "../form.setup";
// The inputs hold strings; the schema trims the name and parses the age
const signupSchema = type({
name: type("string.trim").to(type("string > 0").configure({ message: "Name is required" })),
email: type("string.email").configure({ message: "Invalid email" }),
// the message goes on the type that checks it (after the parse)
age: type("string.integer.parse").to(type("number >= 18").configure({ message: "Must be 18 or older" })),
});
export default function SignupForm() {
const [output, setOutput] = useState<typeof signupSchema.infer>();
return (
<Form
schema={signupSchema}
defaultValues={{ name: "", email: "", age: "" }}
config={{
name: { type: "text", label: "Name" },
email: { type: "text", label: "Email" },
age: { type: "text", label: "Age", props: { inputMode: "numeric" } },
}}
// `data` is the schema output: the name trimmed, the age a number
onSubmit={(data) => setOutput(data)}
>
<button type="submit">Sign up</button>
{output && <pre data-testid="output">{JSON.stringify(output)}</pre>}
</Form>
);
}
pnpm add yup. Yup casts while validating, so onSubmit gets the cast values.
import { useState } from "react";
import * as yup from "yup";
import { Form } from "../form.setup";
// Yup (1.7+) implements Standard Schema: it goes straight into `schema`.
// It casts while validating: the name is trimmed and the age becomes a number.
const signupSchema = yup.object({
name: yup.string().trim().required("Name is required"),
email: yup.string().required("Email is required").email("Invalid email"),
age: yup.number().typeError("Must be 18 or older").integer().min(18, "Must be 18 or older").required(),
});
export default function SignupForm() {
const [output, setOutput] = useState<yup.InferType<typeof signupSchema>>();
return (
<Form
schema={signupSchema}
defaultValues={{ name: "", email: "", age: undefined }}
config={{
name: { type: "text", label: "Name" },
email: { type: "text", label: "Email" },
age: { type: "text", label: "Age", props: { inputMode: "numeric" } },
}}
// `data` is the schema output: the name trimmed, the age a number
onSubmit={(data) => setOutput(data)}
>
<button type="submit">Sign up</button>
{output && <pre data-testid="output">{JSON.stringify(output)}</pre>}
</Form>
);
}
pnpm add effect. Schema.toStandardSchemaV1 turns the schema into a Standard Schema; Schema.FiniteFromString parses the age while decoding.
import { Schema } from "effect";
import { useState } from "react";
import { Form } from "../form.setup";
// Effect Schema implements Standard Schema through `toStandardSchemaV1`.
// The inputs hold strings; decoding trims the name and parses the age.
const signupSchema = Schema.toStandardSchemaV1(
Schema.Struct({
name: Schema.Trim.check(Schema.isNonEmpty({ message: "Name is required" })),
email: Schema.String.check(Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, { message: "Invalid email" })),
age: Schema.FiniteFromString.annotate({ message: "Must be 18 or older" }).check(
Schema.isInt({ message: "Must be 18 or older" }),
Schema.isGreaterThanOrEqualTo(18, { message: "Must be 18 or older" }),
),
}),
);
export default function SignupForm() {
const [output, setOutput] = useState<(typeof signupSchema)["Type"]>();
return (
<Form
schema={signupSchema}
defaultValues={{ name: "", email: "", age: "" }}
config={{
name: { type: "text", label: "Name" },
email: { type: "text", label: "Email" },
age: { type: "text", label: "Age", props: { inputMode: "numeric" } },
}}
// `data` is the decoded output: the name trimmed, the age a number
onSubmit={(data) => setOutput(data)}
>
<button type="submit">Sign up</button>
{output && <pre data-testid="output">{JSON.stringify(output)}</pre>}
</Form>
);
}
pnpm add ajv ajv-errors ajv-formats @hookform/resolvers. Handy when the JSON Schema comes from a backend; coerceTypes turns the age string into a number.
import { ajvResolver } from "@hookform/resolvers/ajv";
import type { JSONSchemaType } from "ajv";
import { useState } from "react";
import { Form } from "../form.setup";
type Signup = { name: string; email: string; age: number };
// A JSON Schema (for example served by a backend), validated with Ajv through
// `formOptions.resolver`. `errorMessage` (ajv-errors) sets the messages.
const signupSchema: JSONSchemaType<Signup> = {
type: "object",
properties: {
name: { type: "string", minLength: 1, errorMessage: { minLength: "Name is required" } },
email: { type: "string", format: "email", errorMessage: { format: "Invalid email" } },
age: { type: "integer", minimum: 18, errorMessage: "Must be 18 or older" },
},
required: ["name", "email", "age"],
additionalProperties: false,
};
export default function SignupForm() {
const [output, setOutput] = useState<object>();
return (
<Form
// coerceTypes: the age input holds a string; Ajv converts it to a number
formOptions={{ resolver: ajvResolver(signupSchema, { coerceTypes: true }) }}
defaultValues={{ name: "", email: "", age: "" }}
config={{
name: { type: "text", label: "Name" },
email: { type: "text", label: "Email" },
age: { type: "text", label: "Age", props: { inputMode: "numeric" } },
}}
// `data` is what Ajv validated, with the age coerced to a number
onSubmit={(data) => setOutput(data)}
>
<button type="submit">Sign up</button>
{output && <pre data-testid="output">{JSON.stringify(output)}</pre>}
</Form>
);
}
pnpm add joi @hookform/resolvers. Joi converts while validating (trim, string to number); set the messages per error code with .messages().
import { joiResolver } from "@hookform/resolvers/joi";
import Joi from "joi";
import { useState } from "react";
import { Form } from "../form.setup";
type Signup = { name: string; email: string; age: number };
// Joi converts while validating (trim, string to number) and, through
// `formOptions.resolver`, `onSubmit` receives the converted values.
const signupSchema = Joi.object<Signup>({
name: Joi.string().trim().required().messages({ "string.empty": "Name is required" }),
email: Joi.string()
.email({ tlds: false }) // no TLD list in the browser
.required()
.messages({ "string.empty": "Invalid email", "string.email": "Invalid email" }),
age: Joi.number()
.integer()
.min(18)
.required()
.messages({ "number.base": "Must be 18 or older", "number.integer": "Must be 18 or older", "number.min": "Must be 18 or older" }),
});
export default function SignupForm() {
const [output, setOutput] = useState<Signup>();
return (
<Form
formOptions={{ resolver: joiResolver(signupSchema) }}
defaultValues={{ name: "", email: "", age: "" }}
config={{
name: { type: "text", label: "Name" },
email: { type: "text", label: "Email" },
age: { type: "text", label: "Age", props: { inputMode: "numeric" } },
}}
// `data` is what Joi converted: the name trimmed, the age a number
onSubmit={(data) => setOutput(data as unknown as Signup)}
>
<button type="submit">Sign up</button>
{output && <pre data-testid="output">{JSON.stringify(output)}</pre>}
</Form>
);
}
pnpm add superstruct @hookform/resolvers. With coerce: true, trimmed and coerce convert the inputs; a refiner that returns a string fails with that message. Its resolver's output type differs from the inputs, so it is cast once.
import { superstructResolver } from "@hookform/resolvers/superstruct";
import { useState } from "react";
import type { Resolver } from "react-hook-form";
import { type Infer, coerce, define, object, refine, string, trimmed } from "superstruct";
import { Form } from "../form.setup";
// A refiner or validator that returns a string fails with that message
const age = define<number>("age", (value) =>
(typeof value === "number" && Number.isInteger(value) && value >= 18) || "Must be 18 or older",
);
// `trimmed` and `coerce` run with `coerce: true`: the inputs hold strings,
// the name is trimmed and the age parsed
const signupSchema = object({
name: refine(trimmed(string()), "name", (value) => value.length > 0 || "Name is required"),
email: refine(string(), "email", (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) || "Invalid email"),
age: coerce(age, string(), (value) => (value === "" ? Number.NaN : Number(value))),
});
type Signup = Infer<typeof signupSchema>;
type Input = { name: string; email: string; age: string };
// The form holds the inputs (strings); the coerced output reaches onSubmit
const resolver = superstructResolver(signupSchema, { coerce: true }) as unknown as Resolver<Input>;
export default function SignupForm() {
const [output, setOutput] = useState<Signup>();
return (
<Form
formOptions={{ resolver }}
defaultValues={{ name: "", email: "", age: "" }}
config={{
name: { type: "text", label: "Name" },
email: { type: "text", label: "Email" },
age: { type: "text", label: "Age", props: { inputMode: "numeric" } },
}}
// `data` is the coerced output: the name trimmed, the age a number
onSubmit={(data) => setOutput(data as unknown as Signup)}
>
<button type="submit">Sign up</button>
{output && <pre data-testid="output">{JSON.stringify(output)}</pre>}
</Form>
);
}

