Is it possible to validate a field based on another field’s value in custom validation?
Good news - yes, you can definitely validate a field based on another field's value! The key is using the validation context that gets passed to your custom validation function.
Your approach is close, but Rule.valueOfField() isn't the right method. Instead, you need to access the parent document through the context parameter that's passed to your custom validation function. Here's how to fix your code:
{
title: 'Has date end?',
name: 'has_date_end',
type: 'boolean',
fieldset: 'dates',
},
{
name: 'date_end',
type: 'date',
fieldset: 'dates',
validation: (Rule) => Rule.custom((value, context) => {
const hasDateEnd = context?.parent?.has_date_end;
if (hasDateEnd && !value) {
return 'Please provide an end date since "Has date end?" is checked';
}
return true;
})
}The important parts:
- Your custom validation function receives two parameters:
value(the current field's value) andcontext(which contains information about the document) - Access other field values via
context.parent.fieldName - Return
truewhen validation passes - Return an error message string when validation fails
You can also add different validation severity levels if needed:
validation: (Rule) => Rule.custom((value, context) => {
const hasDateEnd = context?.parent?.has_date_end;
if (hasDateEnd && !value) {
return 'Please provide an end date'; // Error (blocks publishing)
}
return true;
}).warning() // Or use .warning() or .info() for different severityFor more complex scenarios, the validation documentation has additional examples, and there's a helpful guide on validation helpers for creating reusable validation functions.
One thing to keep in mind: this validation only runs in the Studio interface. If you're creating/updating documents via the API directly, you'll need to implement validation on the server side as well, since Studio validation is client-side only.
Show original thread3 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.