✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

How to preserve validation on required relational fields after removing the relation

4 replies
Last updated: Feb 4, 2021
So I noticed that when you link a relation as a required field and remove the relation, the validation is still valid
Feb 4, 2021, 9:49 AM
This is likely because
Rule.required
simply checks for existence. Before you click the button, the field itself is undefined, when you click add, but dont input any values, Studio inserts an empty object. The field is now defined with
guide: {}
and since an object is truthy, it passes the validation check.
The solution to this is to chain some more validation-rules or to add a
Rule.custom
if you want more granular control over what is a valid document and what isnt. 🙂
Feb 4, 2021, 10:07 AM
Haakon is spot on 🎯 You could try something like this as a custom rule:
validation: Rule => Rule.custom(field => {
  return field.length > 0
    ? true
    : 'Required'
  }),
Feb 4, 2021, 10:18 AM
Yeah I got it!
Feb 4, 2021, 10:19 AM
thank you all !
Feb 4, 2021, 10:19 AM

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?