
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeGreat question! You can definitely use rule.custom() to create conditional validation based on another field's value. Here's how to do it:
The key is accessing the context parameter in your custom validation function, which gives you access to the parent document and other fields. Here's a practical example:
defineField({
name: 'u',
title: 'U Field',
type: 'string',
validation: (rule) =>
rule.custom((value, context) => {
// Check if field X has a specific value
const xValue = context?.document?.x;
if (xValue === 'someSpecificValue') {
// Make U field required when X is set to this value
if (!value) {
return 'U field is required when X is set to "someSpecificValue"';
}
}
return true; // Valid
}),
})Some important things to note:
Accessing other fields: Use context?.document?.fieldName to access sibling fields at the document level, or context?.parent?.fieldName for fields within the same object/array.
Return values: Your custom function should return:
true when the value is valid{message: 'Error', level: 'error'} for more controlHandling undefined: Always check if values exist since fields might be empty, especially during initial document creation.
Here's a more complete example with different validation levels:
validation: (rule) =>
rule.custom((value, context) => {
const x = context?.document?.x;
if (x === 'critical') {
if (!value) {
return 'U is required when X is critical'; // Error (blocks publishing)
}
} else if (x === 'important') {
if (!value) {
return {
message: 'Consider filling U when X is important',
level: 'warning' // Warning (allows publishing)
};
}
}
return true;
}),You can find more details about custom validation in the official validation documentation and this specific community answer about conditional validation.
Remember that validation only runs in the Studio interface - API mutations bypass these rules, so implement server-side validation if you're accepting content through other channels!
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