Get a peek at our latest innovations at Sanity Product Day on Dec 8th →

Validation Error - Validation Error if Both Fields Are In Use

3 replies
Last updated: Apr 13, 2021

Hi, I'm struggling with validation of two fields. My use-case is; I have two fields. Field A is for internal links and field B is for external links. I would like to show an error if both fields are filed out.
My schema is as follows:


title: "Artikkel",

name: "article",

type: "reference",

to: [{ type: }],

description: "Lenke til en artikkel på Löplabbet",

validation: (_Rule_: _any_) =>

_Rule_.custom((_context_: _any_) =>

_context_.article && _context_.url ? true : "Du kan ikke lenke til både artikkel og ekstern URL"




title: "URL",

name: "url",

type: "string",

description: "Lenke til en ekstern side",

validation: (_Rule_: _any_) =>

_Rule_.custom((_context_: _any_) =>

_context_.url && _context_.article ? true : "Du kan ikke lenke til både ekstern URL og artikkel"



This shows a validation error message if both fields are in use, but I'm not able to publish. And the publish button shows this error: There are validation errors that need to be fixed before this document can be published.

Apr 12, 2021, 5:21 PM

Hi Knut. Are you saying you want there to be a warning message if both fields are filled out but you still want to be able to publish?

Apr 12, 2021, 6:35 PM

You can use document level validation but the warning is a bit out of the way (top-right corner), which is usually fine when it prevents a publish but in this case may go unseen.

fields: [...],
validation: Rule => Rule.custom(fields => (
  fields?.url && fields?.article ? "Du kan ikke lenke til både artikkel og ekstern URL" : true

Apr 12, 2021, 6:58 PM

Thank for your help! I want to prevent a user from being able to publish if both fields are filled out. So by changing

.error("Some message her...")
, solved that.
Again, thanks for your help

Apr 13, 2021, 6:59 AM Get the most out of your content is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Free to get started, and pay-as-you-go on all plans. Find out more.