How to make all properties in Zod schema optional based on specific product availability flag?
P粉298305266
P粉298305266 2023-08-30 22:37:05
0
1
465
<p>I have a Zod schema for validating product attributes for an e-commerce application. In my schema, I currently have an attribute called <code>isLimitedEdition</code> which indicates whether the product is in limited supply. However, when <code>isLimitedEdition</code> is set to true , I want all other properties in the schema to become optional. </p> <p>This is the existing architecture:</p> <pre class="brush:php;toolbar:false;">const productProperties = z.object({ name: z.string().nonempty(), description: z.string().nonempty(), price: z.number().positive(), category: z.string().nonempty(), brand: z.string().nonempty(), isFeatured: z.boolean().default(false), isLimitedEdition: z.boolean().default(false), });</pre> <p>In this architecture, I want to implement a behavior where if isLimitedEdition is set to true, all properties (name, description, price, category, brand, isFeatured) become optional. </p> <p>How can I modify this schema to achieve the desired behavior? I would be grateful for any guidance or code examples to help me implement this logic correctly. Thank you in advance! </p> <p>I tried the <code>refine</code> method without success</p>
P粉298305266
P粉298305266

reply all(1)
P粉225961749

You can use discriminatedUnion to achieve this:

const productProperties = z.object({
  name: z.string().nonempty(),
  description: z.string().nonempty(),
  price: z.number().positive(),
  category: z.string().nonempty(),
  brand: z.string().nonempty(),
  isFeatured: z.boolean().default(false),
})

const product = z.discriminatedUnion('isLimitedEdition', [
  productProperties.extend({ isLimitedEdition: z.literal(false) }),
  productProperties.partial().extend({ isLimitedEdition: z.literal(true) }),
])
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template