Conditional Validation in Form Schema Using Zod?

Hey everyone, I'm currently working on a validation schema for a form in my project, and I'm looking for some guidance on how to implement conditional validation. Here's a simplified version of what I have
export const createSchema = z.object({
method: z.enum(['fixed', 'timed', 'bids']),
price: z.string().optional().or(z.literal('')).transform(value => (value ? String(value) : '')),
title: z.string().min(1, {message: 'Please Enter Title'}),
file: z.instanceof(File, {message: 'Please Select File'}),
preview: z.instanceof(File, {message: 'Please Select Preview'}).nullable(),
})
export const createSchema = z.object({
method: z.enum(['fixed', 'timed', 'bids']),
price: z.string().optional().or(z.literal('')).transform(value => (value ? String(value) : '')),
title: z.string().min(1, {message: 'Please Enter Title'}),
file: z.instanceof(File, {message: 'Please Select File'}),
preview: z.instanceof(File, {message: 'Please Select Preview'}).nullable(),
})
In this schema, I have a method field which can take values 'fixed', 'timed', or 'bids'. What I'm trying to achieve is to make the price field required only when the method is set to 'fixed', otherwise, it should be optional. Could someone please guide me on how to add this conditional validation effectively using zod ? Thanks in advance for your help! 🙏
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server