Is it Possible to Pass a Document Reference to Validation and Access the Dereferenced Fields?

2 replies
Last updated: Aug 6, 2021
Heyyy I have a schema validation question. Is it possible to pass a doc reference to validation and access the dereferenced fields? It seems not. It also seems like the solution is to perform a fetch to get it. Is there anything I'm missing here?
Aug 6, 2021, 6:57 PM
I expect you’re right that a fetch will be involved. I would use the Sanity client and get the data you’re after in that fetch (in my case below, the title). This snippet lets you paste a document _id into a string field and if it exists, it throws a validation error that contains that document’s title. I’d recommend looking at this function to add some robustness to the query:

import sanityClient from 'part:@sanity/base/client';

const client = sanityClient.withConfig({ apiVersion: '2021-08-06' });

// ...

export default {
  name: 'validationTest',
  title: 'Validation Test',
  type: 'document',
  fields: [
      name: 'id',
      title: 'ID',
      type: 'string',
      validation: Rule => Rule.custom(async (doc) => {
        const match = await client.fetch(`*[_id == $id][0] {_id, title}`, { id: doc })
        return !match ? true : `This document already exists. Title: ${match.title}`
Aug 6, 2021, 7:46 PM
thanks, Geoff!
Aug 6, 2021, 8:33 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the 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?