Error in custom validation rule for schema in Slack thread
6 replies
Last updated: Aug 18, 2023
J
Schema validation error. I am trying to write a custom validation rule using the .custom function however I get error
slug: Exception occurred while validating value: name.includes is not a function. (In 'name.includes("Brew")', 'name.includes' is undefined)
slug: Exception occurred while validating value: name.includes is not a function. (In 'name.includes("Brew")', 'name.includes' is undefined)
{ title: "Slug", name: "slug", type: "slug", options: { source: "title", maxLength: 200, // will be ignored if slugify is set 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((name: string) => { if (typeof name === "undefined") { return true; // Allow undefined values } // This would crash if we didn't check // for undefined values first return name.includes("Brew") ? "you can't use Brew" : true; }), ], },
Aug 18, 2023, 2:26 PM
V
Try console.log(name) before the line
And check what is currently name
return name.includes("Brew") ? "you can't use Brew" : true;
Aug 18, 2023, 2:33 PM
J
I See the problem now. Console.log prints
{_type: "slug", current: "jjj"}
so its name.current. only thing is that I lose the typescript definitions for this input type
{_type: "slug", current: "jjj"}
so its name.current. only thing is that I lose the typescript definitions for this input type
Aug 18, 2023, 3:43 PM
V
It’s normal, you typed
Then you can use this type here:
name: string.Try to declare a type before like so:
interface TypeName { _type: 'slug'; current: string; }
Rule.custom((name: TypeName) => {…
Aug 18, 2023, 3:46 PM
J
Thanks very much
Aug 18, 2023, 4:06 PM
J
Here is the finished custom rule that checks that the slug is all lowercase and no special characters except -
validation: (Rule) => [ Rule.required(), Rule.custom((name: { _type: string; current: string }) => { // This would crash if we didn't check // for undefined values first if (typeof name === "undefined") { return true; // Allow undefined values } let hasSpecialCharacters = /[^\na-z0-9-]/g.test(name.current); return hasSpecialCharacters ? "Your slug has characters that are not allowed" : true; }), ], },
Aug 18, 2023, 4:08 PM
V
Top! congrats
Aug 18, 2023, 4:18 PM
Sanity– build remarkable experiences at scale
Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.