Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Use the validation status of a document in your custom document actions

By Saskia Bobinska

When creating custom document actions, it can be necessary to check, wether all validation rules are full-filled.

Use validation status of a document in custom document actions

// sanity.config.ts
...,
document: {
  actions: (actions, context) => {
		// we can even only add this action to a specific subset of doc types
    if (context.schemaType === 'article') return [...actions, creatValidationAction(context)]
   else return actions
      },
    },
...


// creatValidationAction.ts

import {isValidationErrorMarker} from '@sanity/types'
import {
  DocumentActionComponent,
  DocumentActionProps,
  DocumentActionsContext,
  useValidationStatus,
} from 'sanity'

export function createPreviewEmailAction(context: DocumentActionsContext): DocumentActionComponent {
  // this action function has to return a function, that in turn returns an object
  const id = context.documentId as string
  const schemaType = context.schemaType as string

  return (props: DocumentActionProps) => {

    // check if Validation is ongoing and get the errors (and check if there are true errors)
    const validationStatus = useValidationStatus(id, schemaType)
    const hasValidationErrors = validationStatus.validation.some(isValidationErrorMarker)

    return {
      label: 'Validation Based Action!',
      disabled: hasValidationErrors,
      onHandle: () => {
				// add your custom logic here
        console.log('This is validated and can be executed')
      },
    }
  }
}

Contributor

Other schemas by author