
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeYou'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:
context.getClient() to get a configured Sanity client within your validation functionasync since you're fetching datavalue._ref to query for the documenttrue for valid or an error string for invalidYou 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 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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store