Go Behind the Experience to see how Tecovas brings the West to life with Sanity 🤠 July 18th

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: articleDocument.name }],

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
)).warning()
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
.warning()
to
.error("Some message her...")
, solved that.
Again, thanks for your help
😃
Apr 13, 2021, 6:59 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?