The Sanity engineering blog is live. Deep dives from our engineers.

Validating unique hospital names in Sanity documents not working

16 repliesLast updated: Nov 29, 2025

can anyone guide me on how to validate uniqueness in a document i have tried but not working I want to validate hospital namesvalidation: Rule => Rule.required().custom((input)=>{       
          return client.fetch(
count(*[_type == "hospitalManagement" &&amptitle == "${input}"])
)          .then(count  =>  {
            if (count > 0){
              return 'Title needs to be unique'
            }else{
              return true
            }
          })
        })
AI Update

I can see the issue with your validation code. There are a few problems that need to be fixed for the uniqueness validation to work properly.

The main issues are:

Here's the corrected version:

validation: Rule => Rule.required().custom(async (input, context) => {
  const client = context.getClient({apiVersion: '2021-03-25'})
  
  // Get the current document ID to exclude it from the search
  const currentDocId = context.document._id
  
  const query = `count(*[_type == "hospitalManagement" && title == $title && _id != $currentId])`
  const params = {
    title: input,
    currentId: currentDocId.replace('drafts.', '') // Remove 'drafts.' prefix if present
  }
  
  const count = await client.fetch(query, params)
  
  if (count > 0) {
    return 'Hospital name must be unique'
  }
  return true
})

Key changes:

The validation will now properly check if another document (excluding the current one) already has the same hospital name.

You can read more about custom validation and asynchronous validation using the client in the Sanity documentation.

Show original thread
16 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