Admin collection level validation

default discord avatar
wezzle2 years ago
1 1

Is it possible to do validation on Collection level in the admin? We have two fields:

  • Link: relationship
  • Title: text

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.

  • Selected Answer
    default discord avatar
    rpfaeffle2 years ago

    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");
              }
            }
          },
        ],
      },
    }
    1 reply
  • default discord avatar
    wezzle2 years ago

    Thank you for the APIError example. I'll use this for now!

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.