Get current user inside validation for role-based rules
Unfortunately, you cannot directly access the current user context inside validation functions in Sanity. The validation function's context parameter only provides access to document data (like parent and document), not user information.
From the validation documentation, the context object in validation functions includes things like the parent object and document values, but not the current user.
However, there are several alternative approaches you can use to achieve role-based validation:
Alternative Approaches
1. Use Custom Input Components with User Context
Custom input components have access to the current user via the useCurrentUser() hook. You can apply different validation logic or UI based on roles:
import { useCurrentUser, StringInputProps } from 'sanity'
export function RoleBasedInput(props: StringInputProps) {
const currentUser = useCurrentUser()
const isAdmin = currentUser?.roles.some(role => role.name === 'administrator')
// Apply different validation or UI based on role
// ...
}2. Use readOnly or hidden Callbacks
The readOnly and hidden field options do receive user context through their callback functions. This won't provide validation messages, but can prevent unauthorized editing:
defineField({
name: 'sensitiveField',
type: 'string',
readOnly: (context) => {
const userRoles = context.currentUser?.roles.map(r => r.name) || []
return !userRoles.includes('administrator')
}
})3. Store User Info in the Document
As shown in the Studio customizations course, you can store user information in the document itself, then reference it in validation:
defineField({
name: 'createdBy',
type: 'string',
initialValue: (params, context) => context.currentUser?.id,
hidden: true
}),
defineField({
name: 'someField',
type: 'string',
validation: (rule) => rule.custom((value, context) => {
const createdBy = context.document?.createdBy
// Apply different validation rules based on createdBy
if (createdBy === 'specific-user' && !value) {
return 'This field is required for you'
}
return true
})
})4. Backend Validation with Document Actions or Functions
For critical validation that must be enforced server-side, use custom document actions or Sanity Functions to validate on publish. Functions can access the authenticated user making the request and enforce rules accordingly.
Remember that Studio-level validation is primarily for user experience - backend validation ensures data integrity regardless of who's editing.
The combination of readOnly/hidden callbacks with custom input components is usually the most practical approach for role-based field control in the Studio!
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.