Custom validation messages for specific fields in document-level validation
I apologize for the confusion in my previous answer! You're absolutely right that the syntax wasn't working. The correct property is path (singular), not paths, and it takes a single array of path segments, not a nested array.
Here's the correct syntax for document-level validation that targets a specific field:
validation: (rule) => rule.custom((document) => {
return myCondition
? { message: 'Your error message', path: ['name-of-the-field'] }
: true;
})Notice it's path: ['fieldName'] with a single array, not paths: [['fieldName']].
For nested fields, you'd structure the path array with multiple segments:
// For a nested field like document.author.name
path: ['author', 'name']
// For an array item with a specific _key
path: ['items', { _key: 'abc123' }, 'title']Here's a complete working example from the official documentation:
export default defineType({
name: 'post',
type: 'document',
title: 'Blog Post',
validation: (rule) =>
rule.custom((fields) => {
if (
fields.authors.length > 0 &&
Object.keys(fields.guest).length > 0
)
return {
message: "You can't have an author AND guest author",
path: ['guest'], // Error appears on the guest field
}
return true
}),
fields: [
defineField({
name: 'authors',
title: 'Authors',
type: 'array',
of: [{ type: 'authorReference' }],
}),
defineField({
name: 'guest',
title: 'Guest Author',
type: 'object',
fields: [
defineField({ name: 'name', type: 'string', title: 'Guest Author Name' }),
defineField({ name: 'site', type: 'string', title: 'Guest Author Site' }),
],
}),
],
})Key points:
- Use
path(singular), notpaths(plural) - The value is a single array of path segments:
['fieldName'] - For nested fields, add more segments:
['parent', 'child'] - This validation goes on the document type itself, not on individual fields
- The path must exactly match your field names (case-sensitive)
The validation documentation section on "Marking nested fields as invalid" shows this pattern clearly. The confusion comes from the "Validating children" section which uses paths (plural) for array validation, but for document-level validation targeting specific fields, you need path (singular).
This should make your validation error appear directly on the targeted field instead of just in the document-level top bar!
Show original thread2 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.