✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

Custom validation on array length

By William Iommi

Simple custom validation that force array length according to another field.

TemplateGallery.ts

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.

Contributor

Other schemas by author

Is your Microcopy unique?

A custom validation to check if your Microcopy documents have unique keys and values for a specific namespace.

William Iommi
Go to Is your Microcopy unique?