How to make a field required or set default values in Sanity Studio
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 thread1 reply
Was this answer helpful?
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.