@sonardigital/zod-validations
v1.0.2
Published
Type-safe validation utilities and patterns powered by Zod. Use the same schemas for runtime validation and static TypeScript inference in Node.js, Express, Next.js, and more.
Downloads
2
Readme
zod-validation
Type-safe validation utilities and patterns powered by Zod. Use the same schemas for runtime validation and static TypeScript inference in Node.js, Express, Next.js, and more.
Why Zod
- Define schemas once; get both runtime checks and inferred types.
- Helpful error messages with paths and issues.
- Composable primitives for objects, arrays, enums, unions, refinements, and effects.
Installation
This project is built around zod.
npm i zod
# or
pnpm add zod
# or
yarn add zodIf you are consuming this package as a library, also install it:
npm i zod-validation zodQuick start
Define a schema and validate input.
import { z } from 'zod';
const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
age: z.number().int().min(13).optional(),
});
type User = z.infer<typeof UserSchema>;
// Throws a ZodError when invalid
const user: User = UserSchema.parse(payload);
// Non-throwing alternative
const result = UserSchema.safeParse(payload);
if (!result.success) {
console.error(result.error.format());
} else {
// result.data is typed as User
}Common patterns
Express request validation
import { z } from 'zod';
import type { Request, Response, NextFunction } from 'express';
const CreateUserBody = z.object({
email: z.string().email(),
password: z.string().min(8),
});
function validateBody<T extends z.ZodTypeAny>(schema: T) {
return (req: Request, res: Response, next: NextFunction) => {
const parsed = schema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ errors: parsed.error.format() });
}
req.body = parsed.data;
next();
};
}Next.js (App Router) route handler
import { z } from 'zod';
import { NextResponse } from 'next/server';
const Params = z.object({ id: z.string().uuid() });
export async function GET(_req: Request, ctx: { params: unknown }) {
const parsed = Params.safeParse(ctx.params);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
}
const { id } = parsed.data;
return NextResponse.json({ id });
}Narrowing with preprocess and transforms
const PageQuery = z.object({
page: z.preprocess((v) => Number(v), z.number().int().min(1).default(1)),
});Error handling tips
- Use
error.format()for a nested, serializable structure. - Use
error.flatten()for a flat structure with fieldErrors and formErrors. - Prefer
safeParsein HTTP handlers to avoid throwing.
Development
- Requires Node.js 18+.
- Uses TypeScript for types-first development.
Contributing
Issues and PRs are welcome. Please include a minimal repro for bugs and keep changes focused.
License
MIT
