How AI is powering better personalization in e-commerce [with Vercel]. Sign up now

Custom validation on array length

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

By William Iommi


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

William Iommi

Junior/Senior/Lead Frontend @ Syskoplan Reply IT

Italy

Visit William Iommi's profile