Schema Validate With Zod Safe Parse

Validate form input with Zod schemas using safeParse for typed error collection and automatic type narrowing.

JavascriptForm Validation

Code

javascriptsnippet
1 line
import{z}from'zod';const userSchema=z.object({email:z.string().email(),age:z.number().int().min(18).max(120),role:z.enum(['admin','user','guest'])});export function validateUser(input){const result=userSchema.safeParse(input);if(!result.success){return{success:false,errors:result.error.issues.map(i=>({path:i.path.join('.'),message:i.message}))};}return{success:true,data:result.data};}

How the snippet works

Schema Validate With Zod Safe Parse is built around the function validateUser.

The import line is the dependency contract: z comes from zod and nothing else.

The result comes back as an object carrying true.

Points of care

  • Plan for an install step: zod is a real dependency, resolved by the package manager.
  • The guard !result.success short-circuits the flow with an early return when its condition holds.

Applying it

The main signature reads export function validateUser(input)

validateUser is the public entry point; everything else in the file exists to support it.

The call returns true.

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `zod`. Add it to your project before running the snippet.
What does `validateUser` return?
An object carrying `true`.