Checking if a field is hidden and making it required if not.
18 replies
Last updated: Jun 1, 2022
L
Is there any way of checking whether a field is
hiddenfor making it required if it isn't?
documentdoesn't seem to contain any value regarding the
hiddenstatus of a field.
Jun 1, 2022, 8:15 AM
K
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
L
Would a required hidden field still be required?
Jun 1, 2022, 8:19 AM
K
Pretty sure it would.
Jun 1, 2022, 8:20 AM
L
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
For context, this is basically about conditional fields for a link type: internalLink & externalLink
Jun 1, 2022, 8:22 AM
L
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
K
Ah I see. Yes that makes sense.
Jun 1, 2022, 8:24 AM
L
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
L
Seems they are staying required even if hidden.
Jun 1, 2022, 8:25 AM
L
Having a boolean exposed on children of
documentwould be awesome.
Jun 1, 2022, 8:26 AM
L
I can actually see a
hiddenfield there but I think it refers to something else?
Jun 1, 2022, 8:26 AM
L
Content:
Jun 1, 2022, 8:27 AM
L
ref => { var parent = _ref.parent; return (parent === null || parent === void 0 ? void 0 : parent.linkType) !== "external";
Jun 1, 2022, 8:27 AM
L
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
L
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
L
I think I will give the "isItEmpty" check a shot first.
Jun 1, 2022, 8:31 AM
L
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,
Thank you for the help,
user F
! 🙂Jun 1, 2022, 8:37 AM
K
Yay! Glad you got it. 😊
Jun 1, 2022, 8:38 AM
L
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.