Discussion on validating uniqueness of hospital names in a document, with code snippets provided.
16 replies
Last updated: Jul 27, 2021
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:
- String interpolation syntax: You're using
"${input}"instead of proper template literal syntax with backticks - 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
- 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:
- Use backticks for the GROQ query string (template literals)
- Use parameterized queries (
$titleand$currentId) instead of string interpolation - this is safer and handles special characters properly - Exclude the current document with
_id != $currentIdso you don't count the document being edited - Handle draft IDs by removing the
drafts.prefix when comparing IDs - Make the function
asyncand useawaitfor 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.
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.