Issue with Desk tool crashing when deleting the last document in an array-type field.
This is a known issue with custom validation functions in Sanity Studio when working with array fields. The problem occurs because your domainRestrictionsValidator function is likely trying to access the length property of the array value without first checking if the value exists or is an array.
When you delete the last item from an array field, Sanity may pass undefined or null to your validation function rather than an empty array, causing the "Cannot read properties of undefined (reading 'length')" error.
The Fix
You need to add defensive checks in your validation function to handle undefined, null, or empty array cases. Here's how to update your validation:
{
name: 'domain',
type: 'array',
title: 'Domain',
of: [{ type: 'restricted_domain' }],
validation: (Rule) =>
Rule.custom((value) => {
// Handle undefined, null, or empty array cases
if (!value || !Array.isArray(value) || value.length === 0) {
return true; // or return an error message if the field should be required
}
// Now safely call your validator
return domainRestrictionsValidator(value);
}),
}If your domainRestrictionsValidator is a separate function, update it to include similar guards:
const domainRestrictionsValidator = (value) => {
// Guard clause for undefined/null/empty
if (!value || !Array.isArray(value) || value.length === 0) {
return true;
}
// Your actual validation logic here
// Now you can safely access value.length and iterate
// ...
};Why This Happens
As mentioned in the Sanity validation documentation, when a field is empty or undefined, the validation function still runs but receives undefined as the value. Your validator needs to explicitly handle this case by returning true (valid) for undefined values, unless you want the field to be required when empty.
The key principle from Sanity's validation system is: always check if the value exists before trying to access its properties. This is especially important for arrays, objects, and other complex types that might be undefined during editing operations.
You can also use optional chaining if you just need to check length in a simple way:
validation: (Rule) =>
Rule.custom((value) => {
if (value?.length === 0 || !value) {
return true;
}
return domainRestrictionsValidator(value);
}),This pattern prevents the crash and allows the array to be properly emptied without breaking the Desk tool.
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.