Conditional validation of string
Validate a field only if a sibling boolean type is set to true.
By Geoff Ball
conditionalValidation.js
export default {
name: "docName",
title: "Document Name",
type: "document",
fields: [
{
name: 'flag',
title: 'Flag for Validation',
type: 'boolean',
},
{
name: 'entry',
type: 'string',
title: 'Entry',
validation: Rule => Rule.custom((field, context) => (context.document.flag && field === undefined) ? "This field must not be empty." : true),
},
],
};There may be cases where a field should only be validated when flagged. This short snippet will require a non-empty field entry only when flag is set to true.
If flag is set to false, entry will not be validated (i.e., the string can be empty).
Contributor

Geoff Ball
Support Engineer at Sanity.io
Canada