Passing parent object attributes to child fields in Sanity schema
Unfortunately, Sanity schemas don't support directly passing down attributes from parent fields to child fields the way you might pass props in React. The schema definition is a static configuration object, not a component tree with props flowing down.
However, there are a few approaches you can use to achieve similar validation patterns:
1. Access Parent Context in Validation
The validation Rule provides access to parent field values through the context parameter. You can reference the parent's value in child field validation:
{
name: 'someField',
type: 'array',
of: [{
type: 'object',
fields: [
{
name: 'maxLength',
type: 'number'
},
{
name: 'child',
type: 'string',
validation: (Rule) => Rule.custom((value, context) => {
// Access the parent object (the array item)
const maxLength = context.parent?.maxLength
if (maxLength && value && value.length > maxLength) {
return `Must be ${maxLength} characters or less`
}
return true
})
}
]
}]
}The context parameter in validation functions gives you access to:
context.parent- the immediate parent objectcontext.document- the entire document being edited
2. Use Shared Validation Functions
If you need to reuse the same validation logic across multiple fields, define it as a function:
const createMaxLengthValidation = (maxLength: number) => {
return (Rule) => Rule.max(maxLength)
}
// Then use it in multiple places
{
name: 'field1',
type: 'string',
validation: createMaxLengthValidation(50)
},
{
name: 'field2',
type: 'string',
validation: createMaxLengthValidation(50)
}3. Dynamic Validation Based on Document Fields
For validation that depends on other parts of the document, use context.document:
{
name: 'child',
type: 'string',
validation: (Rule) => Rule.custom((value, context) => {
const configValue = context.document?.someConfigField
if (configValue && value && value.length > configValue) {
return `Must be ${configValue} characters or less`
}
return true
})
}The key limitation is that schema definitions are static - you can't reference parent.customAttribute directly in the schema object. But you can access parent and document values dynamically at validation time through the context parameter, which should help you implement validation at the lowest field level without complex nested validation logic.
Show original thread6 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.