👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Error in custom validation rule for schema in Slack thread

6 replies
Last updated: Aug 18, 2023
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)


{
      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
Try console.log(name) before the line
return name.includes("Brew") ? "you can't use Brew" : true;
And check what is currently name
Aug 18, 2023, 2:33 PM
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
Aug 18, 2023, 3:43 PM
It’s normal, you typed
name: string
.Try to declare a type before like so:

interface TypeName {
  _type: 'slug';
  current: string;
}
Then you can use this type here:
Rule.custom((name: TypeName) => {
Aug 18, 2023, 3:46 PM
Thanks very much
Aug 18, 2023, 4:06 PM
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
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.

Was this answer helpful?