Astro uses Zod to power its content schemas, which allows you to validate every file’s frontmatter within a collection and provide automatic TypeScript types when you query content from inside your project.
In your case, you want to conditionally validate the name field based on the discriminant field under parent. You can achieve this by using Zod's .refine() method to create a custom validation rule. Here's an example of how you can define your schema:
import { defineCollection, z } from 'astro:content';
const blogCollection = defineCollection({
schema: z.object({
parent: z.object({
discriminant: z.boolean(),
name: z.string().optional().refine((name, parent) => parent.discriminant === true ? name !== undefined : true, {
message: "Name must be provided when discriminant is true",
}),
}),
}),
});
export const collections = { blog: blogCollection };
In this schema, name is optional but it must be provided when discriminant is true. If discriminant is false, name can be omitted.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: