Zod Schema Parse With Transform
Define Zod schemas with transforms for input normalization validation and output type inference.
Code
import{z}from'zod';export const userSchema=z.object({email:z.string().email().transform(s=>s.toLowerCase()),age:z.number().int().min(18).max(120),tags:z.array(z.string()).default([]),metadata:z.record(z.string(),z.unknown()).optional()}).strict();export type User=z.infer<typeof userSchema>;export function parseUser(input:unknown):User{return userSchema.parse(input);}export function safeParseUser(input:unknown){const result=userSchema.safeParse(input);return result.success?{valid:true,data:result.data}:{valid:false,errors:result.error.issues};}How it works
Zod Schema Parse With Transform is built around the functions parseUser and safeParseUser.
From zod it pulls z — the imports name exactly which library surface the snippet touches.
Watch out for
- Plan for an install step:
zodis a real dependency, resolved by the package manager.
Putting it to use
The main signature reads export const userSchema=
The surface worth importing is userSchema; the helpers around it are private to the snippet.
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `zod`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.