Unlock seamless workflows and faster delivery with our latest releases- get the details

Issue with validation in array of references in a document field definition.

2 replies
Last updated: Mar 10, 2023
Is it possible to make a document invalid if an array of references contains an empty reference? This is my field definition:
{
  name: 'types',
  title: 'Product type',
  description: 'You can select multiple types for compound products.',
  type: 'array',
  of: [
    defineArrayMember({
      type: 'reference',
      to: [{type: 'productType'}],
      options: {disableNew: true},
    }),
  ],
  validation: (Rule) => Rule.required().unique().error('Cannot add same product type twice'),
},
Unfortunately the validation is not working as I expect. The user can still click on "Add item" in the array, leave the reference input untouched and publish the document…
Mar 10, 2023, 9:52 AM
You should be able to use a custom validator to map over each of the product items and check if they all have a "_ref" property. You could use something like
item.hasOwnProperty('_ref')
or
"_ref" in item
to check.
https://www.sanity.io/docs/validation#091e10f957aa
Mar 10, 2023, 10:46 AM
Thanks User, I made it work with this info. I still believe it should be easier to mark a document as not publishable if there is a ref pointing to nothing. 🙂
Mar 10, 2023, 11:31 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?