Is it Possible to Pass a Document Reference to Validation and Access the Dereferenced Fields?
You're absolutely right – reference fields in Sanity validation don't automatically dereference, and using Rule.custom() with a fetch is indeed the standard solution for this.
When you access a reference field in validation, you only get the reference object itself (with _ref, _type, etc.), not the actual referenced document's fields. To access those fields, you need to fetch the referenced document using the Sanity client.
Here's the pattern using Rule.custom() with the validation context:
defineField({
name: 'authorRef',
type: 'reference',
to: [{type: 'author'}],
validation: (rule) =>
rule.custom(async (value, context) => {
if (!value?._ref) return true;
const client = context.getClient({apiVersion: '2024-01-01'});
const author = await client.fetch(
`*[_id == $id][0]{name, isActive}`,
{id: value._ref}
);
if (!author?.isActive) {
return 'Please select an active author';
}
return true;
}),
})The key things to know:
- Use
context.getClient()to get a configured Sanity client within your validation function - Make the validation function
asyncsince you're fetching data - Access the reference ID via
value._refto query for the document - Return
truefor valid or an error string for invalid
You can also access other document fields through context.document or the parent value through context.parent, which is useful for conditional validation based on other fields in your document.
One thing to watch out for: these validation functions run client-side in the Studio, so fetching on every keystroke could impact performance. Consider debouncing or only validating on blur if you're doing expensive queries.
There's no built-in "auto-dereference" option for validation – the fetch approach is the intended pattern for accessing referenced document data during validation.
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.