✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

Optional validation for hidden fields

By Daniel Favand

We can turn off validation for fields using the same logic we use to hide them

Document definition with fields that are not required when hidden

// This is the shared logic for whether the mightBeHidden field is visible and required
const shouldShow = (document) => {
  return document.conditionField === 'show'
}

export default {
  type: 'document',
  name: 'myDocumentType',
  title: 'My Document Type',
  fields: [
    {
      // when you enter "show" into this text field,
      // the mightBeHidden field will appear and be required
      type: 'string',
      name: 'conditionField',
      title: 'Condition Field',
    },
    {
      type: 'string',
      name: 'mightBeHidden',
      title: 'Might Be Hidden',
      validation: (rule) =>
        rule.custom((currentValue, {document}) => {
          // in a custom validation rule, check if the field should be shown, and if yes, show an error if the value is not set
          if (shouldShow(document) && currentValue === undefined)
            return "This is required when conditionField === 'show'"
          // if we are not showing the field, or if the field has a value
          // then the validation passes
          return true
        }),
      hidden: ({document}) => {
        // use the shared function to decide whether to show the field
        return !shouldShow(document)
      },
    },
  ]
}

Validations in the studio start from the premise that the validation should pass regardless of the UI state. For example, a field might be hidden because of an author's role or because other content has not been filled in, but still required for publishing.

However, sometimes when a field is hidden it is also not required. In this case we can use the same logic to control the validation and whether the field is hidden. This makes the logic of the validation more explicit, as you will define that this field is only required in certain conditions.

Contributor

Other schemas by author