Custom validation rules based on another field's value
Great 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:
truewhen the value is valid- An error message string when invalid
- You can also return an object like
{message: 'Error', level: 'error'}for more control
Handling 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!
Show original thread11 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.