đź‘‹ Next.js Conf 2024: Come build, party, run, and connect with us! See all events

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:
https://www.sanity.io/docs/validation
What might be helpful is passing in the
context
as the second param - then you can check any fields in your document.
If your using
custom
validation I dont think you can use the
Rule.validationType
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
context
tip is great and will come handy for future work as well
Sep 12, 2020, 10:58 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?