
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeLooking at your code, the issue is likely that you're trying to access properties on children that might be undefined or empty. The error is probably "Cannot read properties of undefined" when trying to access .text on first or last.
Here's the corrected validation function with proper null/undefined checks:
validation: (Rule) => Rule.required().custom((blocks) => {
const offendingPaths = (blocks || [])
.filter(({ _type, children }) => {
if (_type !== "block" || !children || children.length === 0) return false;
const { 0: first, length, [length - 1]: last } = children;
// Check if first/last exist and have text property before checking whitespace
return (first?.text && first.text.startsWith(" ")) ||
(last?.text && last.text.endsWith(" "));
})
.map((block, index) => [{ _key: block._key }] || [index]);
return (
offendingPaths.length === 0 || {
message: "Blocks cannot start or end with whitespace",
paths: offendingPaths,
}
);
})The key changes:
children.length === 0 check: Ensures children array isn't empty before trying to access its elementsfirst?.text.startsWith(" ") to first?.text && first.text.startsWith(" ") to ensure text property exists before calling string methods on itThe original sanity-pills blockValidator.js code works in many cases, but Portable Text blocks can have edge cases where children spans don't have a text property (like inline objects or custom marks), which causes the error you're seeing.
This validation approach is useful for maintaining clean content in your Portable Text fields, ensuring editors don't accidentally leave trailing or leading spaces that could cause formatting issues in your frontend.
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