-
Is it possible to do validation on Collection level in the admin? We have two fields:
We want to validate that either the Link or Title field is filled in. Title is optional once you provide a Link (as the linked collection has a title field) but is required if you do not provide a link relationship. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
As far as I know, there is no possibility to validate a collection directly, based on the properties you hand over to fields. But you could use a I've created a simple example using a const Collection = {
slug: 'my-collection',
fields: [
{
name: "checkbox",
type: "checkbox",
},
{
type: "text",
name: "text",
required: false, // Important, else you won't be able to save
},
],
hooks: {
beforeValidate: [
({ data }) => {
if (data?.checkbox && data.checkbox === true) {
// Make sure text has value
if (!data.text || data?.text.trim() === "") {
throw new APIError("Text is required");
}
}
},
],
},
} |
Beta Was this translation helpful? Give feedback.
As far as I know, there is no possibility to validate a collection directly, based on the properties you hand over to fields. But you could use a
BeforeValidateHook
to check whether a link has been provided or not. The only problem with this is that you have to make both of the fields optional and cannot directly show the user that the field is required (except you're using a custom component). But you could throw and error message using payloadsApiError
to provide the user with context why it failed to save.I've created a simple example using a
checkbox
and atextfield
: