Required Relation Field

For me, the undocumented feature of simply setting required: true worked up until 4.5.0 where https://github.com/strapi/strapi/pull/14401/ was released.

With that PR the content manager started submitting more complex object as the value for relations fields even if the value is empty. Unfortunately, this object passes through the required validator as it merely checks the value isn’t null or undefined.

BTW, if you implemented this check manually in your controllers and you really need to enforce this invariant you should consider if your check handles this new syntax. It goes roughly like this:

relation_attribute: { 
  connect: [<ids to attach>],
  disconnect: [<ids to detach>)
}

Note that this syntax is “procedural” - it doesn’t state what the resulting data should be, but rather describes how to achieve the desired state by a set of updates. This makes a robust required check quite hard to pull-off as you’d have to first pull the current state of the entity from the DB, run the proposed updates, and only then check if the result is empty or not. If you think that embedding a procedural syntax inside a REST API is unfortunate well, you’re not alone. :man_shrugging:

2 Likes