Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

How to access collection slug in validate function?

default discord avatar
jacko49last year
2

Anyone have success with this? Can't access via request because it hasn't resolved when validate runs.



This is what i've tried but breaks:



validate: async (val, options) => {
      const slug = options.req.collection.config.slug;
      if (val === "resources" && slug === "checklist-items" ) {
        return true;
      } else if (val === "resources") {
        return "Resource type is not valid for this collection"
      }
    }


Thanks!

  • default discord avatar
    ritsu0455last year

    If you need this only for collections, not for globals, you can try to retrieve slug from

    req.baseUrl

    like this


    const slug = options.req.baseUrl?.replace("/api/", "")


    or with 3.0 and next js it's easier


    const { collection } = options.req?.routeParams ?? {}

    but honestly it's not that good solution to rely on

    req

    because you can also use Local API for your operations, only if you are sure that you won't.


    If you need this for a custom field that you will use for multiple collections differently (i don't know other cases why you ask this), i would just pass collection slug to a field's creator function.


    const field = ({ slug }: { slug: string }): TextField => ({
      type: 'text',
      name: 'field',
      validate: () => {
        if (slug === '...') return 'Error'
        return true
      },
    })
  • default discord avatar
    jacko49last year

    @ritsu thanks for the help, went with the option you suggested in the code snippet, worked like a charm 🍻

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.