🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

How to prevent self-reference in child-parent setup in Sanity using custom validation or filter option.

4 replies
Last updated: Sep 7, 2023
Hi everyone, I'm new to Sanity trying to setup a child parent reference (category / subcategory) but how do I prevent a self reference?
Sep 6, 2023, 3:58 PM
using custom validation. you can simply look at the document using context to determine if the category can be set. https://www.sanity.io/docs/validation#091e10f957aa
Sep 6, 2023, 4:28 PM
the third example down shows that the second parameter of the custom method is
Sep 6, 2023, 4:29 PM
Or use filter option on the reference object to filter out the current document’s id from the list.

Sep 7, 2023, 4:58 AM
Thanks all,
user P
that was also the solution I found easiest:

filter: ({document}) => {
          return {
            filter: '!defined(parent) && _id != $id',
            params: {
              id: document._id
Sep 7, 2023, 8:44 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?