William Iommi
Lead Frontend @ Portaltech IT
William is located at Milan, Italy
Simple custom validation that force array length according to another field.
import { defineField, defineType } from 'sanity';
export default defineType({
type: 'document',
name: 'templateGallery',
title: 'Template Gallery',
fields: [
// ...
// some other fields
// ...
defineField({
type: 'boolean',
name: 'isLanding',
title: 'Landing',
}),
defineField({
type: 'array',
name: 'gallerySlot',
title: 'Gallery slot',
of: [
{
type: 'reference',
to: [
{
type: 'gallery',
},
],
},
],
validation: (Rule) =>
Rule.custom((value, { document }) => {
if (value && value?.length > 1 && !document?.isLanding) {
return 'This is not a landing page. You can insert only one gallery.';
}
return true;
}),
}),
],
});
Let's imagine we're modeling a template for a gallery page.
The template is used both for the landing, which contains all the available galleries and for the detail page of a single gallery.
In the latter case, however, we want max one gallery to be present in our array field.
This simple custom validation allows you to limit the length of the array field based on another field present in the document.
Lead Frontend @ Portaltech IT
A little 'hack' when you work on custom Document actions
Go to 'Hacking' custom Document Actions πA custom validation to check if your Microcopy documents have unique keys and values for a specific namespace.
Go to Is your Microcopy unique?