Required object with optional fields #2751
-
Hi I noticed something unexpected when trying to validate objects and fields. In the particular case, I had an object with few random fields, one field was itself an object that was required, but had all of its internal fields defined as optional. I would have expected this to work, but zod parse throws an error. Example:
Then trying to validate it, when both fields of field2 are there it works, when one is missing it fails:
My expectation would be that either fields of Is there something that I'm doing wrong, or is this expected? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
https://github.com/colinhacks/zod#required
Try doing something like this: const schema = z.object( {
field2: z.object( {
first: z.string(),
second: z.string(),
} ).partial(),
} )
console.log( schema.parse( { field2: { first: 'foo', second: 'bar' } } ) ) // { field2: { first: 'foo', second: 'bar' } }
console.log( schema.parse( { field2: { first: 'bar' } } ) ) // { field2: { first: 'bar' } }
console.log( schema.parse( { field2: {} } ) ) // { field2: {} }
const result = schema.safeParse( {} )
!result.success && console.log( result.error.issues )
// [
// {
// code: "invalid_type",
// expected: "object",
// received: "undefined",
// path: [ "field2" ],
// message: "Required"
// }
// ] If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
-
Is this what you are looking for? const schema = z.object( {
field2: z.union( [
z.object( { first: z.string(), second: z.string() } ),
z.object( { first: z.string() } ),
z.object( { second: z.string() } ),
] )
} )
console.log( schema.safeParse( { field2: { first: 'bar' } } ).success ) // true
console.log( schema.safeParse( { field2: { second: 'bar' } } ).success ) // true
console.log( schema.safeParse( { field2: { first: 'foo', second: 'bar' } } ).success ) // true
console.log( schema.safeParse( { field2: {} } ).success ) // false If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
-
how about using const example = z.object({
field1: z.string().optional(),
field2: z.object({ first: z.string(), second: z.string()}).partial(),
field3: z.number().optional()
})
// both true
example.safeParse({ field1: 'something', field2: { first: 'bar', second: 'bar'}, field3: 123})
example.safeParse({ field1: 'something', field2: { first: 'bar'}, field3: 123}) |
Beta Was this translation helpful? Give feedback.
Is this what you are looking for?
If you found my answer satisfactory, please consider supporting me. Even a sm…