Prevent duplicate references in Sanity array field
Yes, 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:
- Extracting all the collection reference IDs from your array items
- Checking if any ID appears more than once
- Returning an error message if duplicates are found, or
trueif all are unique
The 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.
Show original thread7 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.