How to allow unique values in an array in Sanity.io schema.
Looking at your code, you're trying to ensure that only one header and one footer can be added to the array. The Rule.unique() method you're using is actually for ensuring array items are unique within that array, but what you want is to limit each type to appearing only once.
Here's the correct approach - use custom validation on the array itself:
export default defineType({
title: 'Component Builder',
name: 'pageBuilder',
type: 'array',
of: [
{
type: 'header',
},
{
type: 'footer',
},
],
validation: Rule => Rule.custom((items) => {
if (!items) return true;
const headerCount = items.filter(item => item._type === 'header').length;
const footerCount = items.filter(item => item._type === 'footer').length;
if (headerCount > 1) {
return 'Only one header is allowed';
}
if (footerCount > 1) {
return 'Only one footer is allowed';
}
return true;
})
})This custom validation function:
- Filters the array items by
_typeto count how many of each type exist - Returns an error message if more than one header or footer is found
- Otherwise returns
trueto indicate the validation passed
The validation will run whenever someone tries to add items to the array and will prevent publishing if they try to add multiple headers or footers. The editor will see a clear error message telling them what the limit is.
Note that Rule.unique() is meant for ensuring values within an array don't duplicate (like ensuring all items in a tags array are different), not for limiting how many times a specific type appears. That's why you need the custom validation approach shown above.
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.