Skip to content

Conditional validation #2099

Discussion options

You must be logged in to vote

Is this what you are looking for?

const props = {
    name: z.string(),
    wings: z.number(),
    legs: z.number(),
}

const typeEnum = z.enum( [ 'mammal', 'bird', 'fish' ] )

const mammalSchema = z.object( {
    type: z.literal( typeEnum.enum.mammal ),
    name: props.name,
    legs: props.legs,
} )

const birdSchema = z.object( {
    type: z.literal( typeEnum.enum.bird ),
    name: props.name,
    legs: props.legs,
    wings: props.wings,
} )

const fishSchema = z.object( {
    type: z.literal( typeEnum.enum.fish ),
    name: props.name,
} )

const animal = z.discriminatedUnion( 'type', [
    mammalSchema,
    birdSchema,
    fishSchema,
] )

Additional resources:
discriminated-unions
W…

Replies: 5 comments 6 replies

Comment options

You must be logged in to vote
2 replies
@markomitranic
Comment options

@RobertaMelo
Comment options

Answer selected by JacobWeisenburger
Comment options

You must be logged in to vote
1 reply
@blntgvn42
Comment options

Comment options

You must be logged in to vote
3 replies
@blntgvn42
Comment options

@zeekrey
Comment options

@gianhunn
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet