Unlock seamless workflows and faster delivery with our latest releases – get the details

Checking if a field is hidden and making it required if not.

18 replies
Last updated: Jun 1, 2022
Is there any way of checking whether a field is
hidden
for making it required if it isn't?

document
doesn't seem to contain any value regarding the
hidden
status of a field.
Jun 1, 2022, 8:15 AM
Considering you know the logic about the hidden field, do you need to check if it’s hidden at all? Can’t you apply the same logic for your validation?
Jun 1, 2022, 8:18 AM
Would a required hidden field still be required?
Jun 1, 2022, 8:19 AM
Pretty sure it would.
Jun 1, 2022, 8:20 AM
Then I would need to know if it is hidden. Or I could conditionally make it required if the other field is empty.
For context, this is basically about conditional fields for a link type: internalLink & externalLink
Jun 1, 2022, 8:22 AM
I could make both required if both are empty. And make the hidden one not required if the other one has content.
Jun 1, 2022, 8:23 AM
Ah I see. Yes that makes sense.
Jun 1, 2022, 8:24 AM
But that might lead to a bit of confusion as both would be shown as required if none is provided. Although that might be compensated with a custom validation message.
Jun 1, 2022, 8:24 AM
Seems they are staying required even if hidden.
Jun 1, 2022, 8:25 AM
Having a boolean exposed on children of
document
would be awesome.
Jun 1, 2022, 8:26 AM
I can actually see a
hidden
field there but I think it refers to something else?
Jun 1, 2022, 8:26 AM
Content:
Jun 1, 2022, 8:27 AM
ref => {
      var parent = _ref.parent;
      return (parent === null || parent === void 0 ? void 0 : parent.linkType) !== "external";
Jun 1, 2022, 8:27 AM
That should simply be my current hidden condition function. Hm. Could I execute this check as well in the validation function and get a boolean back?
Jun 1, 2022, 8:28 AM
As I would be working with
refs
, I would need to use the
sanity.client
, but this seems to be only the function, so I would still need to get access to it as well.
Jun 1, 2022, 8:30 AM
I think I will give the "isItEmpty" check a shot first.
Jun 1, 2022, 8:31 AM
Actually you are right. I can also check using the same logic for validation. I make it required depending on the selected linkType.
Thank you for the help,
user F
! 🙂
Jun 1, 2022, 8:37 AM
Yay! Glad you got it. 😊
Jun 1, 2022, 8:38 AM
The solution for future generations:

validation: (Rule) =>
        Rule.custom((currentValue, { parent }) => {
          return parent?.linkType === "internal" && !currentValue
            ? "A link value is required."
            : true
        }),
Jun 1, 2022, 8:56 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?