
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeYes, you can prevent duplicate references in an array using custom validation! Sanity's validation system supports this through the custom() method that can check for unique values.
Here's how to prevent duplicate collection tags from being added to your image array:
defineField({
name: 'imageTags',
type: 'array',
of: [
{
type: 'object',
fields: [
{
name: 'image',
type: 'reference',
to: [{type: 'image'}]
},
{
name: 'collection',
type: 'reference',
to: [{type: 'collection'}]
}
]
}
],
validation: (rule) => rule.custom((items) => {
if (!items) return true;
// Extract all collection reference IDs
const collectionIds = items
.map(item => item.collection?._ref)
.filter(Boolean);
// Check for duplicates
const duplicates = collectionIds.filter(
(id, index) => collectionIds.indexOf(id) !== index
);
if (duplicates.length > 0) {
return 'Each collection can only be used once';
}
return true;
})
})This validation works by:
true if all are uniqueThe validation runs in real-time as editors add items, and will prevent publishing if duplicates exist. You can also use a more nuanced approach with different severity levels:
validation: (rule) => rule.custom((items) => {
// ... same duplicate check logic ...
if (duplicates.length > 0) {
return {
message: 'Each collection should only be used once',
level: 'warning' // or 'error' or 'info'
};
}
return true;
})Using 'warning' instead of 'error' would allow publishing but still alert the user, while 'info' would just provide helpful guidance.
Keep in mind that validation only runs in the Studio interface - if you're creating content via API, you'll need separate server-side validation as mentioned in the field validation documentation.
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store