How to make a field required or set default values in Sanity Studio

1 replies
Last updated: May 10, 2021
In sanity studio how do you make a field required so that they cant leave it blank or make a default entry, eg the slug field is automatically generated using the title
AI Update

Great question! There are two different things you're asking about - making fields required and setting default/auto-generated values. Let me cover both:

Making Fields Required

To make a field required in Sanity Studio, you use the validation property with the Rule.required() method:

defineField({
  name: 'title',
  type: 'string',
  validation: (rule) => rule.required(),
})

You can also add a custom error message:

validation: (rule) => rule.required().error('Title is required before publishing')

Important note: This validation only works in the Studio interface. API mutations bypass these rules, so if you're creating content via the API, you'll need separate server-side validation.

Auto-Generating Slug from Title

For slug fields specifically, Sanity has a built-in slug field type that provides a "Generate" button and can automatically create URL-friendly slugs from another field:

defineField({
  name: 'slug',
  type: 'slug',
  options: {
    source: 'title',
    maxLength: 96,
  },
  validation: (rule) => rule.required(),
})

The source option tells it which field to use when generating the slug. You can even use multiple fields:

options: {
  source: (doc) => `${doc.title} ${doc.date}`,
}

Setting Default Values with initialValue

For other fields where you want a default value, use the initialValue property on defineField:

defineField({
  name: 'status',
  type: 'string',
  initialValue: 'draft',
})

For more complex defaults, you can use a function:

defineField({
  name: 'publishedAt',
  type: 'datetime',
  initialValue: () => new Date().toISOString(),
})

The initialValue sets the value when a new document is created, while validation rules ensure the field meets requirements before publishing. Together, they give you powerful control over your content structure!

Show original thread
1 reply
Hi
user V
! You can do this by adding a required validation rule to the field, here is an example:
    {
      title: 'slug',
      name: 'slugName',
      type: 'slug',
      validation: (Rule) => Rule.required(),
    },
Here is the documentation on validation for further context:
https://www.sanity.io/docs/validation Also, here is documentation for the slug field that provides the validation and options available specifically for slugs:
https://www.sanity.io/docs/slug-type I hope this helps!

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?