Input validation
Validate an identifier received from an API or form.
Zod · Module
z.nanoid() creates a Zod schema for validating Nano ID strings. Use it wherever a schema is needed, including object fields and collections.
z.nanoid() creates a string schema for Nano IDs. Parsing succeeds only for values that satisfy Nano ID validation; the schema can be composed with object schemas and used with standard Zod parsing methods.
z.nanoid()A Zod schema that validates Nano ID strings.
import { z } from "zod";
const id = z.nanoid();
console.log(id.safeParse("V1StGXR8_Z5jdHi6B-myT").success); // true
console.log(id.safeParse("not-a-valid-nanoid").success); // falseCreates a Zod schema that accepts valid Nano ID strings and rejects values that do not match the Nano ID format.
Validate an identifier received from an API or form.
Require Nano ID identifiers in a Zod object schema.
Validate multiple Nano IDs in one value.
z.nanoid() do?z.nanoid() defines a schema for validating Nano ID strings. It can be parsed directly or embedded in larger Zod schemas.
Follow-up: How would you validate an object identifier? Use z.object({ id: z.nanoid() }) and parse the input.
z.nanoid() instead of z.string()?It is intended for Nano ID values rather than arbitrary strings. Invalid input is rejected through Zod's normal validation behavior.
Follow-up: How can rejection be handled without throwing? Call .safeParse() and inspect its success result.
z.nanoid() be combined with other schemas?The schema is composable, so it can be used anywhere a Zod schema is accepted, including object properties and arrays.
Follow-up: How would you validate several IDs? Use z.array(z.nanoid()).
z.string()z.uuid()z.ulid()z.cuid()z.cuid2()z.string().regex()