When using the Zod library in TypeScript to validate an object with optional properties, it is essential for me to ensure that the object contains at least one property. My goal is to validate the object's structure and confirm that it adheres to a specific format while still allowing certain properties to be optional.
Consider the following example representing the structure of the object I am dealing with:
interface MyObject {
prop1?: string;
prop2?: number;
// Additional optional properties...
}
I am looking for a way to utilize Zod in defining a validation schema that permits optional properties but mandates that at least one property must be present within the object.
How can this requirement be met using Zod? Any advice or code snippets demonstrating how to establish such a schema and subsequently validate the object would be greatly appreciated.
Previously, I attempted to define the schema as shown below:
z.object({
prop1: z.string().optional(),
propt2: z.string().optional(),
});
However, there were instances where the validation did not account for data absence, resulting in acceptance even when no data was provided.