Error in custom validation rule for schema in Slack thread
I can see the issue you're encountering. The problem is that in your custom validation rule, you're checking the name parameter, but for a slug field, the value structure is different than you might expect.
When validating a slug field, the value passed to your custom validation function is not a simple string—it's an object with a current property that contains the actual slug string.
Here's what's happening:
Rule.custom((name: string) => {
// `name` here is actually an object like { _type: 'slug', current: 'some-slug' }
// NOT a string, so name.includes() fails
return name.includes("Brew") ? "you can't use Brew" : true;
})The Solution
You need to access the current property of the slug object:
{
title: "Slug",
name: "slug",
type: "slug",
options: {
source: "title",
maxLength: 200,
slugify: (input: string) => {
const sanitized = input
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^a-zA-Z0-9-]/g, "")
.slice(0, 200);
return sanitized;
},
},
validation: (Rule) => [
Rule.required(),
Rule.custom((slug) => {
if (typeof slug === "undefined") {
return true; // Allow undefined values
}
// Access the 'current' property which contains the actual slug string
if (!slug?.current) {
return true;
}
return slug.current.includes("brew")
? "You can't use 'brew' in the slug"
: true;
}),
],
}Key changes:
- Access
slug.currentinstead of treating the value as a string directly - Check if
slug?.currentexists before calling.includes() - Note: I changed the check to lowercase
"brew"since your slugify function converts everything to lowercase
The slug field stores its value as an object: { _type: 'slug', current: 'your-slug-here' }, which is why you need to access the current property. You can see this structure in the Sanity slug type documentation.
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.