0

I'm using the Zod library in TypeScript to validate an object with optional properties. However, I need to ensure that the object has at least one property present. I want to validate the object's structure and ensure that it follows a certain format while allowing some properties to be optional.

Here's an example of the object structure I'm working with:

interface MyObject {
  prop1?: string;
  prop2?: number;
  // Additional optional properties...
}

I would like to use Zod to define a validation schema that allows for optional properties but enforces the requirement that at least one property must be present in the object.

How can I achieve this using Zod? I would appreciate any guidance or code examples on how to define such a schema and validate the object accordingly.

I tried

z.object({
  prop1: z.string().optional(),
  propt2: z.string().optional(),
});

but sometimes when I don't pass data I accepts it

1 Answers1

0

You can add a custom refinement to make sure that the object has at least 1 property by making sure that at least 1 value isn't undefined

const foo = z.object({
  prop1: z.string().optional(),
  propt2: z.string().optional(),
}).refine((obj) => {
  for (const val of Object.values(obj)) {
    if (val !== undefined) return true;
  }
  return false;
}, {
  message: "Object must have at least one property defined"
});
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34