How to make fields required based on a boolean value in a Slack thread.
8 replies
Last updated: Oct 10, 2023
S
Can I make fields required only if a boolean is set to true? Trying to set all fields to required if the banner is enabled.
defineField({ title: "Enable cookie banner", name: "cookie_banner_enabled", type: "boolean", group: "cookies" }), defineField({ title: "Cookie banner title", description: "The title of the cookie banner", name: "cookie_banner_title", type: "string", group: "cookies", hidden: ({ document }) => !document?.cookie_banner_enabled }), defineField({ title: "Cookie banner button text", description: "The text of the cookie banner button if empty defaults to 'Accepteren'", name: "cookie_banner_button_text", type: "string", group: "cookies", hidden: ({ document }) => !document?.cookie_banner_enabled }), defineField({ title: "Privacy Policy link text", description: "The privacy policy link text if empty defaults to 'Privacy Policy'", name: "privacy_link_text", type: "string", group: "cookies", hidden: ({ document }) => !document?.cookie_banner_enabled }), defineField({ title: "Privacy Policy URL", description: "The URL to your privacy policy page.", name: "privacy_url", type: "reference", group: "cookies", to: [{ type: "page" }], hidden: ({ document }) => !document?.cookie_banner_enabled }),
Oct 10, 2023, 9:54 AM
L
validation: (Rule) => Rule.custom((value, context) => { if (context.parent.externalLink) { return true } if (!value) return "This field is required" return true }),
Oct 10, 2023, 11:26 AM
L
If sibling externalLink is false, this field is required
Oct 10, 2023, 11:27 AM
S
On what field should this validation go? Thank you for the help
Oct 10, 2023, 11:28 AM
L
Write it in the same way as the "hidden" property
Oct 10, 2023, 11:29 AM
S
defineField({ title: "Cookie banner title", description: "The title of the cookie banner", name: "cookie_banner_title", type: "string", group: "cookies", hidden: ({ document }) => !document?.cookie_banner_enabled, validation: (Rule) => Rule.custom((value, context) => { if (value && context?.document?.cookie_banner_enabled) { return true } if (!value) return "This field is required" return true }) }),
Oct 10, 2023, 11:31 AM
L
I think you can remove the first
value &&?
Oct 10, 2023, 11:38 AM
L
But yes that looks good
Oct 10, 2023, 11:38 AM
S
defineField({ title: "Cookie banner title", description: "The title of the cookie banner", name: "cookie_banner_title", type: "string", group: "cookies", hidden: ({ document }) => !document?.cookie_banner_enabled, validation: (Rule) => Rule.custom((value, context) => { if (context?.document?.cookie_banner_enabled && !value) { return "Cookie banner title is required" } return true }) }),
Oct 10, 2023, 11:53 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.