Add custom validation logic to your Zod schemas in Express Zod API
Refinements allow you to implement additional validation logic beyond Zod’s built-in validators. They’re useful for business rules, complex constraints, and custom validation that depends on multiple fields.
Use .refine() to add custom validation to any Zod schema:
Copy
Ask AI
import { z } from "zod";import { Middleware } from "express-zod-api";const nicknameConstraintMiddleware = new Middleware({ input: z.object({ nickname: z .string() .min(1) .refine( (nick) => !/^\d.*$/.test(nick), "Nickname cannot start with a digit", ), }), handler: async ({ input }) => { // nickname is guaranteed not to start with a digit return {}; },});
import { ez } from "express-zod-api";z.object({ startDate: ez.dateIn(), endDate: ez.dateIn(),}).refine( (data) => data.endDate > data.startDate, "End date must be after start date",)
z.object({ type: z.enum(["email", "phone"]), email: z.string().email().optional(), phone: z.string().optional(),}).refine( (data) => { if (data.type === "email") return !!data.email; if (data.type === "phone") return !!data.phone; return true; }, "Email is required when type is 'email', phone is required when type is 'phone'",)