Add validation rule to ensure string starts and ends with specific character
You can use Sanity's custom validation with the custom() method to enforce that a string starts and ends with a specific character. Here's how to validate that slugs begin and end with /:
defineField({
name: 'slug',
title: 'Slug',
type: 'string',
validation: (rule) =>
rule.custom((slug) => {
// Allow undefined/empty values if the field is optional
if (!slug) {
return true;
}
// Check if slug starts and ends with /
if (!slug.startsWith('/') || !slug.endsWith('/')) {
return 'Slug must begin and end with a forward slash (/)';
}
return true;
}),
})If you want to make the field required AND enforce the slash rule, you can chain the validations:
defineField({
name: 'slug',
title: 'Slug',
type: 'string',
validation: (rule) => [
rule.required().error('Slug is required'),
rule.custom((slug) => {
if (!slug) return true; // Let the required() rule handle empty values
if (!slug.startsWith('/') || !slug.endsWith('/')) {
return 'Slug must begin and end with a forward slash (/)';
}
return true;
}).error('Invalid slug format'),
],
})This validation will prevent users from saving or publishing the document until they add the required slashes at both ends. The error message will appear in real-time as they type, giving them immediate feedback.
You can also use a regex pattern if you prefer:
validation: (rule) =>
rule.custom((slug) => {
if (!slug) return true;
const regex = /^\/.*\/$/;
return regex.test(slug) ? true : 'Slug must begin and end with /';
}),The custom validation documentation provides more details on creating validation rules tailored to your specific requirements.
Show original thread8 replies
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.