Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do not allow extra properties with zod parse

I’m using zod for validation. It seems like if I define a schema and then parse() some input with some extra properties that aren’t even in the schema, zod parses the input as valid but just removes those keys.

import { z } from 'zod'

const schema = z.object({
  foo: z.string(),
  bar: z.number()      
})

// this validates fine, printing { foo: 'hello', bar: 1 }
console.log(schema.parse({ foo: 'hello', bar: 1, baz: true })) 

However, extra input properties is not something I’d like to ignore, instead I’d like to throw a useful error when that happens, reporting the keys of the extra properties.

Is there a way to do that with zod?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the strict option:

const schema = z.object({
  foo: z.string(),
  bar: z.number()      
}).strict();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading