How to Require a Field Conditionally with Custom Validation
Yes, absolutely! You can make validation conditional by using the custom() validation method and checking the value of isSubDepartment through the validation context.
Here's how to modify your parentDepartment field:
{
name: 'parentDepartment',
title: 'Parent Department',
type: 'reference',
to: [{ type: 'departments' }],
options: {
filter: 'isSubDepartment == $isSubDepartment',
filterParams: { isSubDepartment: false },
},
hidden: ({ parent }) => !parent?.isSubDepartment,
validation: (Rule) =>
Rule.custom((value, context) => {
// Only require the field if isSubDepartment is truthy
if (context.parent?.isSubDepartment && !value) {
return 'Parent Department is required when this is a sub-department';
}
return true;
}),
}The key here is that the custom validation function receives a context parameter that includes parent, which gives you access to the sibling fields in your object. You can check context.parent?.isSubDepartment to determine whether the field should be required.
If isSubDepartment is true and the field is empty, the validation returns an error message. Otherwise, it returns true to indicate the field is valid.
This approach is much more flexible than Rule.required() because you have full programmatic control over when the requirement applies. You can also adjust the error message to be more specific to your use case, which helps guide your content editors.
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.