#required field in collection only when content is published?

3 messages · Page 1 of 1 (latest)

keen condor
#

I was wondering if there's a way to let some field to be required only if another field has a certain value? To make it clear : I want to be able to save incomplete content if it's still a draft, but when it's published then all required fields should be verified. Without it, at the moment I can't create new content without needing to complete required fields with dummy stuff.

grave summitBOT
#

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

#

Astro's content collections feature allows you to define a schema for your content, which enforces consistent frontmatter or entry data within a collection. This schema guarantees that the data exists in a predictable form when you need to reference or query it. If any file violates its collection schema, Astro will provide a helpful error to let you know. However, the schema does not currently support conditional requirements based on the value of another field. All fields defined in the schema are required regardless of the state of the content (draft or published) source (https://docs.astro.build/en/guides/content-collections#defining-a-collection-schema).

As a workaround, you can use the getCollection() function with a filter callback to filter out draft content when querying your collection. This way, you can prevent any draft content from being published to your site. Here's an example:

// Example: Filter out content entries with `draft: true`
import { getCollection } from 'astro:content';
const publishedBlogEntries = await getCollection('blog', ({ data }) => {
  return data.draft !== true;
});

source (https://docs.astro.build/en/guides/content-collections#filtering-collection-queries)

This doesn't directly solve your problem of needing to fill in required fields with dummy data for draft content, but it does allow you to work with draft content in your development environment without it being published in production.

For more advanced validation rules like the one you're describing, you might need to implement a custom validation function in your application code.

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