search

Home  >  Q&A  >  body text

How to make all properties in Zod schema optional based on specific product availability flag?

<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粉298305266P粉298305266453 days ago425

reply all(1)I'll reply

  • P粉225961749

    P粉2259617492023-08-31 17:26:21

    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) }),
    ])

    reply
    0
  • Cancelreply