Sanity Pioneers: Get early access to betas, extra AI credits, and a direct line to the engineering team. Apply now

Validate unique boolean field across documents in Sanity schema

3 repliesLast updated: Nov 29, 2025

Hello there, i have a schema in which a field of
boolean
contain named as isFeatured. Now i want to do validation like if isFeatured is true in any doument, i shouldn't be able to make isFeatured true in any other document and it should show which document has already isFeatured true. How to add this kinda validation. Thanks.
AI Update

You can achieve this with a custom validation rule that queries your dataset to check if any other document has isFeatured set to true. Here's how to implement it:

defineField({
  name: 'isFeatured',
  type: 'boolean',
  title: 'Featured',
  validation: (Rule) =>
    Rule.custom(async (value, context) => {
      // Only validate if isFeatured is being set to true
      if (!value) return true

      // Get the Sanity client
      const client = context.getClient({ apiVersion: '2023-01-01' })
      
      // Query for other documents with isFeatured = true
      // Exclude the current document using its _id
      const query = `*[_type == $type && isFeatured == true && _id != $id][0...2] {
        _id,
        title
      }`
      
      const params = {
        type: context.document?._type,
        id: context.document?._id || ''
      }
      
      const existingFeatured = await client.fetch(query, params)
      
      // If another document is already featured, show an error
      if (existingFeatured && existingFeatured.length > 0) {
        const doc = existingFeatured[0]
        return `Only one document can be featured at a time. "${doc.title || doc._id}" is already featured.`
      }
      
      return true
    })
})

Key points about this implementation:

Important considerations:

This approach uses custom validation with async operations, which is perfect for cases where you need to validate against other documents in your dataset.

Show original thread
3 replies

Was this answer helpful?

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Related contributions