How to make schema fields required in Sanity?
You're experiencing a common point of confusion with Sanity validation! While you can absolutely make a field required using required: true in your schema, there's an important caveat: validation only works in the Studio interface, not for API mutations.
When you add validation like this:
defineField({
name: 'title',
type: 'string',
validation: (rule) => rule.required(),
})This will prevent editors from publishing documents in the Studio without filling in that field. However, if you're creating or updating documents directly through the API (using the HTTP API, client libraries, or mutations), these validation rules are completely bypassed.
Why This Happens
Sanity's validation is client-side only - it's designed to provide real-time feedback to content editors in the Studio, but it doesn't enforce rules at the database level. This is by design, as it gives you flexibility in how you manage content through different channels.
Solutions
If you need to enforce required fields for API mutations, you have a few options:
- Add server-side validation in your application code before sending mutations to Sanity
- Use Sanity Functions to create event handlers that validate content after mutations and either reject invalid changes or send notifications
- Implement validation in your API layer if you're using a backend that sits between your frontend and Sanity
Here's an example of validating before a mutation:
const doc = {
_type: 'article',
title: formData.title,
slug: formData.slug
}
// Validate before mutating
if (!doc.title || !doc.slug) {
throw new Error('Title and slug are required')
}
await client.create(doc)The key takeaway: Studio validation is for editor experience, but you need separate validation logic for programmatic content creation through the API.
Show original thread5 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.