Dynamic validation for optional object fields in Sanity.io
Yes, you can conditionally validate fields based on whether their parent object is hidden! The key is to use Sanity's custom() validation method and check the parent object's visibility condition within your validation logic.
Here's how to approach this:
Solution: Conditional Validation Based on Parent Visibility
Since validation runs independently of the hidden() function, you need to replicate the same condition in your field validation. Here's a practical example:
{
name: 'myObject',
type: 'object',
hidden: ({document}) => !document?.showAdvancedOptions, // Object is conditionally hidden
fields: [
{
name: 'requiredField',
type: 'string',
validation: (rule) =>
rule.custom((value, context) => {
// Only validate if parent object would be visible
const isParentVisible = context.document?.showAdvancedOptions;
if (!isParentVisible) {
return true; // Skip validation when parent is hidden
}
// Validate normally when parent is visible
return value ? true : 'This field is required';
})
}
]
}Important Considerations
As noted in the conditional fields documentation, hidden fields that are marked as required will still enforce validation, even when hidden. This is a known behavior in Sanity Studio, which is why you need the conditional validation approach above.
Pattern for Complex Scenarios
If your object has multiple fields with validation, you might want to extract the visibility logic into a helper function to keep things DRY:
const isObjectVisible = (context) => {
return context.document?.showAdvancedOptions === true;
};
{
name: 'myObject',
type: 'object',
hidden: ({document}) => !isObjectVisible({document}),
fields: [
{
name: 'field1',
type: 'string',
validation: (rule) =>
rule.custom((value, context) =>
!isObjectVisible(context) || value
? true
: 'Required when object is visible'
)
},
{
name: 'field2',
type: 'string',
validation: (rule) =>
rule.custom((value, context) =>
!isObjectVisible(context) || value
? true
: 'Required when object is visible'
)
}
]
}This approach ensures your validation logic stays synchronized with your visibility conditions, and fields are only validated when their parent object is actually visible to the editor.
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.