Validating unique hospital names in Sanity documents not working

16 replies
Last 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" && title == "${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:

  1. String interpolation syntax: You're using "${input}" instead of proper template literal syntax with backticks
  2. The query will always find at least 1 document: When editing an existing document, it will find itself, so the count will never be 0
  3. You need to exclude the current document from the count

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:

  1. Use backticks for the GROQ query string (template literals)
  2. Use parameterized queries ($title and $currentId) instead of string interpolation - this is safer and handles special characters properly
  3. Exclude the current document with _id != $currentId so you don't count the document being edited
  4. Handle draft IDs by removing the drafts. prefix when comparing IDs
  5. Make the function async and use await for cleaner code

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

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.

Was this answer helpful?