Add validation rule to ensure string starts and ends with specific character

8 replies
Last updated: Nov 29, 2025
How would I go about adding a rule in a sanity field to make sure whatever string is put into that field begins and ends with a certain character?
So for slugs, I want to make sure that when a slug is added, the user adds a beginning and trailing
/
and if they do not it will not allow them to save/publish until they add that.
AI Update

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 thread
8 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.

Was this answer helpful?