Block validator error: whitespace validation function not working
Looking 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:
- Added
children.length === 0check: Ensures children array isn't empty before trying to access its elements - Strengthened the conditional: Changed from
first?.text.startsWith(" ")tofirst?.text && first.text.startsWith(" ")to ensuretextproperty exists before calling string methods on it
The 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.
Show original thread9 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.