Making fields required in Sanity schema using a validation rule

1 replies
Last updated: May 23, 2023
Is there any way to make fields in your schema Required by default? 90%+ or so of our fields should be required, and we’d rather do something like
Rule.optional()
for ones that are not
AI Update

Based on the documentation, no, there isn't a built-in way to make all fields required by default in Sanity schemas. Each field must explicitly define its validation requirements, so you'll need to add .required() to each field individually rather than having an opt-out Rule.optional() approach.

This is mentioned in the Field Validation documentation, which notes that "Sanity doesn't support making fields required by default."

However, there are a few approaches you can take to reduce the repetition:

1. Create a validation helper function:

// lib/validationHelpers.ts
export const defaultValidation = (rule) => rule.required()

// In your schema
defineField({
  name: 'title',
  type: 'string',
  validation: defaultValidation
})

// For optional fields
defineField({
  name: 'subtitle',
  type: 'string',
  // Simply omit the validation property
})

2. Create a field factory function:

// lib/fieldHelpers.ts
export const requiredField = (name, type, overrides = {}) => 
  defineField({
    name,
    type,
    validation: (rule) => rule.required(),
    ...overrides
  })

// Usage
requiredField('title', 'string'),
requiredField('slug', 'slug', { 
  options: { source: 'title' }
}),
defineField({ 
  name: 'optionalField', 
  type: 'string' 
  // No validation = optional
})

3. Use a schema generator or wrapper:

For larger projects, you could create a more sophisticated wrapper that applies required validation by default unless you specify optional: true:

const field = (config) => 
  defineField({
    ...config,
    validation: config.optional 
      ? config.validation 
      : (rule) => {
          const base = rule.required()
          return config.validation ? config.validation(base) : base
        }
  })

// Usage
field({ name: 'title', type: 'string' }), // required
field({ name: 'subtitle', type: 'string', optional: true }), // not required

Keep in mind that validation is client-side only within the Studio, so API mutations will bypass these rules. If you need server-side enforcement, you'll need to implement that separately using Sanity Functions or API hooks.

No, but since the schema is just javascript, you can programmatically add the
required
validation rule by using a function to assign it to the object containing your schema.
Not quite default, but not too much overhead!

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?