See Sanity in action 👀 Join us for a live product demo + Q&A →

Conditionally Making an Alt Text Field Required

3 replies
Last updated: Jan 19, 2023
What would be a good way to conditionally make an alt text field required only if the related image asset is set?
I was trying something like this, but
returns an object that contains
, and no actual `_ref`:
export default defineType({
  name: 'mainImage',
  type: 'image',
  title: 'Image',
  options: {
    hotspot: true,
  fields: [
      name: 'alt',
      type: 'string',
      title: 'Alternative text',
      description: 'Important for SEO and accessibility.',
      validation: (Rule) =>
          (alt, ctx) => {
            // this outputs {type: Symbol(FIELD_REF), path: 'alt'}
            console.log('asset', Rule.valueOfField('asset'))
            // this works as expected, but I need it to work independently from its implementation within a document (as field name might be different)
            console.log('ctx.document', ctx.document)
            if (Rule.valueOfField('asset') && !alt) {
              return 'Alt text is required.'
            return true
As noted there,
has what I would need in the context of that particular document, but I need this to be generally applicable wherever this object type is used.
Jan 18, 2023, 5:06 PM
You can check the
inside of the
instead! Something like this:
      name: 'image',
      type: 'image',
      fields: [
          name: 'alt',
          type: 'string',
          validation: Rule =>
            Rule.custom((value, { parent }) => parent?.asset && value ? true : 'Alt text is required';
Jan 18, 2023, 7:40 PM
TY! That
object did the trick.
Jan 19, 2023, 3:46 AM
And for anyone else who might have similar needs, this is the revised logic I ended up using that covers all the possibilities:
parent?.asset && !value ? 'Alt text is required' : true

Jan 19, 2023, 1:52 PM – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Categorized in