Skip to content

Instantly share code, notes, and snippets.

@SimeonGriggs
Created March 22, 2021 18:03
Show Gist options
  • Save SimeonGriggs/c4c66bc5f6aacea96788248d09862926 to your computer and use it in GitHub Desktop.
Save SimeonGriggs/c4c66bc5f6aacea96788248d09862926 to your computer and use it in GitHub Desktop.
Sanity.io: Extend the built-in `slug` field type with validation rules and slug prefixes
import slugify from 'slugify'
/**
* Slug field which will append a 'prefix' so that your slug is the complete path to the file
* And so that retrieving the slug from a reference to a document is a ready-made link
*
* Example with no prefix:
* `office` becomes `/office`
*
* Example with `office` prefix:
* `sydney` becomes `/office/sydney`
*/
function formatSlug(input, slugStart) {
const slug = slugify(input, { lower: true })
return slugStart + slug
}
export function slugWithType(prefix = ``, source = `title`) {
const slugStart = prefix ? `/${prefix}/` : `/`
return {
name: `slug`,
type: `slug`,
options: {
source,
slugify: (value) => formatSlug(value, slugStart),
},
validation: (Rule) =>
Rule.required().custom(({ current }) => {
if (typeof current === 'undefined') {
return true
}
if (current) {
if (!current.startsWith(slugStart)) {
return `Slug must begin with "${slugStart}". Click "Generate" to reset.`
}
if (current.slice(slugStart.length).split('').includes('/')) {
return `Slug cannot have another "/" after "${slugStart}"`
}
if (current === slugStart) {
return `Slug cannot be empty`
}
if (current.endsWith('/')) {
return `Slug cannot end with "/"`
}
}
return true
}),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment