Is it possible to validate a field based on another field’s value in custom validation?

3 replies
Last updated: Sep 12, 2020

Hello Sanity people đź‘‹
Does anyone know if it’s possible to validate a field based on another field’s value in custom validation?

I have attempted it below but it doesn’t seem to work…

      title: 'Has date end?',
      name: 'has_date_end',
      type: 'boolean',
      fieldset: 'dates',
      name: 'date_end',
      type: 'date',
      fieldset: 'dates',
      validation: Rule => Rule.custom(() => {
        return Rule.valueOfField('has_date_end')
          ? true
          : 'Please check "Has date end?" field'

Sep 12, 2020, 5:29 PM

Yes its possible. Check out this article:
What might be helpful is passing in the

as the second param - then you can check any fields in your document.
If your using
validation I dont think you can use the
but im not too sure on that one.

Sep 12, 2020, 6:54 PM

Something along these lines for custom:

  name: 'durationInMinutes',
  type: 'number',
  title: 'Duration of talk, in minutes',
  validation: Rule => Rule.custom((duration, context) => {
    const isShortTalk = duration && duration <= 10
    if (isShortTalk && context.document.talkType !== 'lightning') {
      return 'Only lightning talks should be 10 minutes or less'
    return true

Sep 12, 2020, 6:55 PM

Wow, thanks Edward! The

tip is great and will come handy for future work as well

Sep 12, 2020, 10:58 PM Get the most out of your content is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Free to get started, pay-as-you-go on all plans.