👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Object level One or the Other validation

By Soufiane

This validation can be used if you have an object with two fields and you require one or the other to be filled

Object level one or the other validation

export default {
  name: "mediaObject",
  title: "My Media Object",
  type: "object",
  fields: [
    {
      name: "videoUrl",
      title: "Video url",
      type: "string",
      validation: (Rule) =>
        Rule.custom((videoUrl, {parent} : any) =>
          typeof parent.image === "undefined" && typeof videoUrl === "undefined"
            ? "Either Video url or Image must have a value"
            : true
        ),
    },
    {
      name: "image",
      title: "Image",
      type: "image",
      validation: (Rule) =>
        Rule.custom((image, {parent} : any) =>
          typeof parent.videoUrl === "undefined" && typeof image === "undefined"
            ? "Either Video url or Image must have a value"
            : true
        ),
    },
  ],
};

There is a snippet about how to do this type of custom validation at the document level by Roboto Studio.

This is the code adapted if you're working on an object instead of a document.

Contributor

Other schemas by author