Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Preventing duplicates of a reference type from being entered into an array in Sanity.io

7 replies
Last updated: Jan 24, 2022
Hey!
Is it possible to prevent duplicates of a reference type from being entered into an array? I'm making a quiz and in the quiz there is a question where a user is allowed to choose images. Each image needs to be tagged with a collection. I'm able to get this to work, but I would like to prevent the tag("collection") from being added to an image more than once. I'll post my code in a comment below.
Jan 24, 2022, 1:46 PM
export default {
  name: "imageOptions",
  title: "Image Options",
  type: "object",
  fields: [
    {
      name: "images",
      title: "Images",
      type: "array",
      of: [
        {
          name: "image",
          title: "Image",
          type: "image",

          fields: [
            {
              name: "alt",
              title: "Alternative text",
              type: "localeString",
            },

            {
              name: "tags",
              title: "tags",
              type: "array",
              of: [
                {
                  type: "reference",
                  to: [{ type: "collections" }],
                },
              ],
            },
          ],
        },
      ],
    },
  ],
};

Jan 24, 2022, 1:46 PM
Hey User. This should be possible by adding a
unique()
validation rule (https://www.sanity.io/docs/array-type#unique()-49ee9907c730 ) to the
tags
array.
You'd add it like this:


{
  name: "tags",
  title: "tags",
  type: "array",
  validation: Rule => Rule.unique(),
  of: [
    {
      type: "reference",
      to: [{ type: "collections" }],
    },
  ],
},
And then you should see that Studio starts validating it accordingly:
Jan 24, 2022, 1:55 PM
WOW!! That is exactly what I needed. Thank you so much for the quick reply.
Jan 24, 2022, 2:00 PM
Can I ask a quick follow up? is it possible to setup the reference as a tags layout? I haven't been able to get it to work.
something like...


 {
              name: "tags",
              title: "tags",
              type: "array",
              options: {
                layout: 'tags'
              },
              validation: Rule => Rule.unique(),
              of: [
                {
                  type: "reference",
                  to: [{ type: "collections" }],
                },
              ],
            }

Jan 24, 2022, 2:02 PM
Unfortunately the tag layout only works for an array of strings at the moment, not references šŸ˜•.
Jan 24, 2022, 2:12 PM
NP, Thanks for the help!
Jan 24, 2022, 2:13 PM
No problem. Let us know if you have any other questions!
Jan 24, 2022, 2:14 PM

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?