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.
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 payloads ApiError
to provide the user with context why it failed to save.
I've created a simple example using a checkbox
and a textfield
:
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");
}
}
},
],
},
}
Thank you for the APIError example. I'll use this for now!
Star
Discord
online
Get dedicated engineering support directly from the Payload team.