Daniel Favand
Solution Engineer at Sanity.io, helping clients build great content experiences.
We can turn off validation for fields using the same logic we use to hide them
// 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.
Solution Engineer at Sanity.io, helping clients build great content experiences.
Fetch content from the base locale regardless of whether the current document is the base or translation document
Go to Query for slugs for all available locales of this documentUsing webhooks and the Sanity API, you can merge content changes and user information
Go to Getting user information with webhooksSimplify finding the right document to select when you have multiple types
Go to Filtering results for reference selectors in arraysOne query to fetch the draft it it exists, and fall back to the published version of a document.
Go to Fetch the draft or published version of a document