🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Conditional validation of string

By Geoff Ball

Validate a field only if a sibling boolean type is set to true.


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).


Other schemas by author

Matching the end of a string in GROQ

GROQ doesn't yet include a function to match the end of a string, but we can simulate it by splitting our string on our term.

Geoff Ball
Go to Matching the end of a string in GROQ