Search code examples
javascriptsanity

Sanity slug validate chars are lowercase


I am building a vue website using sanity as a backend. Instead of rewriting URLS in the router I want to have a pattern in place in sanity where slugs must only be lowercase letters so,

this-is-a-slug-123 would be valid but THIS-is-A-slug-123 would not be valid, I want to do this check as part of the slug validation to stop people being able to save pages with invalid slugs.

Sanity only has the required or custom validation rules available for the type slug. How can I validate the slug is solely using lowercase chars?


Solution

  • You could incorporate a custom validation function that checks against a regex:

    validation: (Rule) => Rule.required().custom((slug) => {
      if (typeof slug === "undefined") return true
      const regex = /(^[a-z0-9-]+$)/ // Regex pattern goes here
      if (regex.test(slug.current)) {
        return true
      } else {
        return "Invalid slug: Only numbers, lowercase letters, and dashes are permitted." // Error message goes here
      }
    }),
    

    This would only validate slugs containing lowercase letters, dashes, and numbers. The regex could be elaborated to account for double dashes, etc., but hopefully this is a start.