Join us live Sept. 27 – How Sanity and Vercel powered Morning Brew's transformation –>

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

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