#Zod for content collection

3 messages · Page 1 of 1 (latest)

velvet path
#

in my content collection i've markdown files in the frontmatter there is a vaue of parent: containting discriminant if discriminant is true than there is one more value called name: string; under it if false than no more values other than discriminant under the parent

parent:
  discriminant: false
parent:
  discriminant: true
  name: news
trail marshBOT
#

Hi @velvet path. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

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.

For more information, you can refer to the Astro documentation on defining datatypes with Zod (https://docs.astro.build/en/guides/content-collections/#defining-datatypes-with-zod) and the Zod documentation (https://github.com/colinhacks/zod).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: