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

Handling optional fields and validation in Sanity.io

9 replies
Last updated: Apr 16, 2021
Is there any way to un-set a value? I have an optional
Call to action
field on an object, and the CTA itself has required fields. I seem to be hitting a weird state where I previously filled them in, but no longer want a CTA on this object, so I've deleted the values.1. I can't un-check a value for "Style"
2. ... which means that the CTA still thinks it's being filled in, and yells at me about the Title + URL being required
Apr 16, 2021, 2:32 PM
Heyo User! Using the Patches API you can unset attributes.
Apr 16, 2021, 5:33 PM
Is there no way to do it automatically? i.e. a way to uncheck a value for those radio boxes?
Apr 16, 2021, 5:35 PM
ahh, maybe the problem is that if I have
layout: 'radio'
you can't unselect a value, but you can with the default string list select.
Apr 16, 2021, 5:36 PM
☝️ was just getting ready type that out. Exactly.
Apr 16, 2021, 5:37 PM
ahh, i like the style of the radios more but I guess I'll switch over, thanks
Apr 16, 2021, 5:37 PM
well, it at least unsets the "style" but still is mad at me about the other fields. is the only solution for this sort of thing adding some sort of "clear CTA" button that fires off a patch?
Apr 16, 2021, 5:38 PM
Does your validation function account for style being blank? Perhaps something like:

validation: (Rule) => Rule.custom(cta => {
  return cta?.style && (!cta?.title || !cta?.url) ? "Fill 'em out!" : true
Apr 16, 2021, 6:10 PM
i just have them as
, so that may be a better solution -- thanks
Apr 16, 2021, 6:40 PM
As an alternative, something like this would provide the more apparent red borders on each field to be validated:

  name: 'title',
  type: 'string',
  title: 'Title',
  validation: (Rule) => Rule.custom((title, { parent }) => {
    return (parent?.style && !title) ? "Title is mandatory." : true
  name: 'url',
  type: 'url',
  title: 'URL',
  validation: (Rule) => Rule.custom((url, { parent }) => {
    return (parent?.style && !url) ? "URL is mandatory." : true
Apr 16, 2021, 6:55 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?