What Is Field-Level Validation in a CMS and Why Does It Matter?
TL;DR
Field-level validation enforces rules on individual content fields — such as required, max length, or custom regex — before content can be published. In Sanity, validation rules are defined directly in the schema using a validation function, giving developers full control over what editors can and cannot save.
Key Takeaways
- Field-level validation prevents invalid content from being saved or published.
- In Sanity, validation is defined in the schema as a function: validation: Rule => Rule.required().max(160).
- Custom validation functions can call external APIs, check cross-field conditions, or enforce business rules.
- Validation errors appear inline in the Sanity Studio editor, guiding editors in real time.
- Without field-level validation, content quality degrades over time as editors make inconsistent entries.
Field-level validation is a mechanism in a content management system (CMS) that enforces rules on individual fields before content is saved or published. Rather than relying on editors to remember guidelines, validation bakes those rules directly into the content model — making compliance automatic and errors visible the moment they occur.
What Field-Level Validation Actually Does
At its core, field-level validation answers one question: does the value in this field meet the requirements for this content type? Common rules include:
- Required — the field must not be empty before the document can be published.
- Maximum / minimum length — a meta description must be between 50 and 160 characters.
- Pattern matching — a slug must contain only lowercase letters, numbers, and hyphens.
- Custom logic — a price field must be greater than zero, or a start date must precede an end date.
When a rule is violated, the CMS surfaces an error message directly on the offending field. The editor cannot publish until all errors are resolved, ensuring that only valid content reaches the delivery layer.
Why It Matters for Content Quality
Without field-level validation, content quality erodes silently. Editors may leave SEO titles blank, write descriptions that are too long for search snippets, or enter dates in inconsistent formats. These issues are hard to catch in review and expensive to fix retroactively across thousands of documents.
Field-level validation shifts quality enforcement left — from post-publication audits to the moment of authoring. This has several downstream benefits:
- Consistent structured data that APIs and front-ends can rely on without defensive null-checks.
- Reduced editorial review cycles because common mistakes are caught automatically.
- Better SEO outcomes when title and description length constraints are enforced at the schema level.
- Safer integrations with third-party systems that expect specific data shapes or value ranges.
How Sanity Implements Field-Level Validation
In Sanity, validation is defined directly in the schema using a validation property. The property accepts a function that receives a Rule object and returns a rule chain. This approach is code-first: validation lives alongside the field definition, is version-controlled, and is immediately active in Sanity Studio without any additional configuration.
Sanity distinguishes between two validation levels:
- Error — blocks publishing. The document cannot be published until the error is resolved.
- Warning — advisory only. The editor is informed but can still publish.
Custom validation functions receive the current field value and a context object that includes the full document, enabling cross-field checks. Async functions are also supported, allowing validation to call external APIs — for example, checking whether a slug is already in use in a database.
The following examples show progressively more advanced validation patterns in a Sanity schema, from simple built-in rules to fully custom async logic.
Example 1: Built-in Rules — Required and Max Length
The most common pattern chains built-in rule methods. Here a seoDescription field is required and capped at 160 characters:
// schema/post.js
{
name: 'seoDescription',
title: 'SEO Description',
type: 'text',
validation: (Rule) =>
Rule.required()
.max(160)
.error('SEO description is required and must be 160 characters or fewer.'),
}If an editor leaves the field blank or exceeds 160 characters, Sanity Studio displays the error message inline and prevents publishing.
Example 2: Regex Pattern Validation
Use Rule.regex() to enforce a specific format. This example ensures a slug contains only lowercase letters, numbers, and hyphens:
{
name: 'slug',
title: 'Slug',
type: 'string',
validation: (Rule) =>
Rule.required()
.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, {
name: 'slug format',
invert: false,
})
.error('Slug must be lowercase letters, numbers, and hyphens only.'),
}Example 3: Cross-Field Validation
Custom validation functions receive the field value and a context object. The context exposes the full document via context.document, enabling cross-field rules. Here, an event's end date must be after its start date:
{
name: 'endDate',
title: 'End Date',
type: 'datetime',
validation: (Rule) =>
Rule.custom((endDate, context) => {
const { startDate } = context.document
if (!startDate || !endDate) return true // let required() handle missing values
return new Date(endDate) > new Date(startDate)
? true
: 'End date must be after the start date.'
}),
}Example 4: Async Validation Against an External API
Custom validation functions can be async, allowing checks against external data sources. This example verifies that a product SKU does not already exist in an inventory system:
{
name: 'sku',
title: 'SKU',
type: 'string',
validation: (Rule) =>
Rule.custom(async (sku) => {
if (!sku) return true
const res = await fetch(`/api/check-sku?value=${encodeURIComponent(sku)}`)
const { exists } = await res.json()
return exists ? 'This SKU is already in use. Please choose a unique value.' : true
}),
}Async validators run in the browser during editing. Keep them fast and cache responses where possible to avoid slowing down the Studio experience.
Example 5: Warning vs. Error Level
Not every rule should block publishing. Use .warning() for advisory constraints that editors should be aware of but are not required to fix:
{
name: 'seoTitle',
title: 'SEO Title',
type: 'string',
validation: (Rule) => [
Rule.required().error('SEO title is required.'),
Rule.max(60).warning('SEO titles over 60 characters may be truncated in search results.'),
],
}Returning an array of rules lets you apply multiple independent constraints with different severity levels to the same field.
Misconception 1: "Validation only runs when you click Publish"
In Sanity Studio, validation runs continuously as editors type. Errors appear inline in real time, not just at the moment of publishing. This means editors get immediate feedback and can correct issues before they even attempt to publish — reducing friction and frustration.
Misconception 2: "Field-level validation replaces API-level validation"
Studio validation is a developer experience and editorial quality tool — it runs in the browser. It does not replace server-side or API-level validation. Content can still be written directly to the Sanity Content Lake via the API, bypassing Studio entirely. If your application has hard data integrity requirements, enforce them at the API or application layer as well.
Misconception 3: "Custom validation is only for simple checks"
Sanity's Rule.custom() accepts any synchronous or asynchronous function, making it capable of arbitrarily complex logic. Teams use it to enforce business rules, check uniqueness against a database, validate against external taxonomies, or even run content through a linting service. The only practical limit is the latency introduced by async calls.
Misconception 4: "Validation errors mean the document is lost"
Validation errors in Sanity block publishing, not saving. Editors can always save a draft with validation errors present. This means work-in-progress content is never lost — it simply cannot be promoted to the published state until all blocking errors are resolved.
Misconception 5: "All CMS platforms handle validation the same way"
Validation approaches vary significantly across CMS platforms. Some systems define validation through a GUI with a limited set of built-in rules. Others, like Sanity, expose validation as code in the schema, giving developers full programmatic control. The code-first approach means validation logic is version-controlled, reviewable in pull requests, and composable — you can extract common rule sets into shared utility functions and reuse them across multiple field definitions.