Check if field is hidden to conditionally make it required
I can see you're trying to conditionally validate a field based on whether it's hidden or not. Unfortunately, there's no built-in way to check if a field is currently hidden within validation rules. The document object available in validation doesn't include the computed hidden state of fields.
However, you can work around this by replicating the same condition logic in both your hidden callback and your validation rule. Here's the pattern:
{
name: 'myField',
type: 'string',
hidden: ({parent}) => parent?.linkType !== 'internal',
validation: (Rule) =>
Rule.custom((currentValue, {parent}) => {
// Replicate the same condition from hidden
const isVisible = parent?.linkType === 'internal';
// Only require if visible
if (isVisible && !currentValue) {
return 'This field is required';
}
return true;
})
}The key insight is that both hidden and validation receive similar context objects (parent, document, value), so you can evaluate the same conditions in both places.
Alternative: Extract the condition
To keep your code DRY and maintainable, you can extract the condition into a helper function:
const isInternalLink = (parent) => parent?.linkType === 'internal';
{
name: 'myField',
type: 'string',
hidden: ({parent}) => !isInternalLink(parent),
validation: (Rule) =>
Rule.custom((currentValue, {parent}) => {
if (isInternalLink(parent) && !currentValue) {
return 'This field is required';
}
return true;
})
}This approach is mentioned in the Sanity docs on conditional fields and discussed in this community answer. While it requires duplicating the logic, it ensures your validation stays in sync with your visibility rules.
Show original thread18 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.