William Iommi
Junior/Senior/Lead Frontend @ Syskoplan CX IT
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.
Junior/Senior/Lead Frontend @ Syskoplan CX IT
A dynamic group filled with fields that don't have any defined group.
Go to Create a dynamic 'Unmapped fields' group in your document definitionA 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?