
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeBased 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:
rule.custom() instead of trying to dynamically chain .max() - custom validation gives you full controlcontext?.parent to read other fields in the same document (like your dropdown)true when valid, or return an error string when invalid (not false)value exists before checking its length to avoid errorsYou 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.
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