Validating with a schema
Validate and type a form with Zod or any other Standard Schema, no plugin needed.
Any Standard Schema validates a form: Zod,
Valibot, ArkType and the rest. Core reads it through the standard interface,
so no plugin is needed. Try admin as the username.
A schema for the form
schema validates the whole value and gives the form its type. Without a
plugin for the schema’s library, defaultValues is required and complete:
import { z } from "zod";
const SignUp = z.object({
username: z.string().min(3, "Use at least 3 characters."),
email: z.email("Enter a valid email."),
});
const signUp = forms.define({
schema: SignUp,
defaultValues: { username: "", email: "" },
onSubmit: (value) => `Signed up ${value.username}.`,
});onSubmit runs only when the schema passes, and gets the schema’s output, so a
transform or a coercion in the schema reaches it. ctx.input holds the value
before the schema ran.
A schema for one field
A schema whose input fits the field’s type can stand in for a validator
function, in validate.fields or in a validate prop:
const signUp = forms.define({
defaultValues: { username: "", email: "" },
validate: { fields: { email: z.email("Enter a valid email.") } },
});The form’s type still comes from defaultValues.
A schema and validators
A definition can have a schema and validators at once, and both run. Use the schema for the shape and validators for what it can’t say well, or for checks that need a request:
const signUp = forms.define({
schema: SignUp,
defaultValues: { username: "", email: "" },
validate: {
fields: {
username: (name) => (name === "admin" ? { message: "That name is reserved." } : undefined),
},
},
});The schema’s errors come first in field.errors, then the form validator’s,
then the field validators’.
Starting values from the schema
Writing defaultValues that match the schema is repetitive for a large form.
The schema plugins work them out from the schema, so
defaultValues becomes optional.
Last updated