Dynamic array max validation based on dropdown selection in Sanity
Based on your question, you're looking to create a custom validation rule for an array where the max length changes based on another field's value (like a dropdown). The key insight is that custom validation functions should return true when valid, or an error string/object when invalid - not a boolean for the invalid case.
Here's how to implement conditional array validation based on another field:
defineField({
name: 'myArray',
type: 'array',
of: [{ type: 'string' }],
validation: (rule) =>
rule.custom((value, context) => {
// Access the parent document to get the dropdown value
const selectedOption = context?.parent?.myDropdown;
// Define your max lengths based on dropdown selection
let maxLength;
switch (selectedOption) {
case 'option1':
maxLength = 3;
break;
case 'option2':
maxLength = 5;
break;
case 'option3':
maxLength = 10;
break;
default:
maxLength = 5; // default max
}
// Check if array exceeds the conditional max
if (value && value.length > maxLength) {
return `Maximum ${maxLength} items allowed for ${selectedOption}`;
}
// Return true if validation passes
return true;
}),
})The critical points here:
- Use
rule.custom()instead of trying to dynamically chain.max()- custom validation gives you full control - Access context: Use
context?.parentto read other fields in the same document (like your dropdown) - Return values: Return
truewhen valid, or return an error string when invalid (notfalse) - Handle undefined: Check if
valueexists before checking its length to avoid errors
You can also add this as an additional validation alongside other rules:
validation: (rule) => [
rule.required(),
rule.custom((value, context) => {
// your conditional logic here
})
]The official validation documentation has more examples, and there's a helpful answer about conditional validation based on other fields that shows similar patterns.
Show original thread4 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.