#How to access collection slug in validate function?

4 messages · Page 1 of 1 (latest)

clear iris
#

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!

ocean shardBOT
#

Help is on the way! To mark it as solved, use the /solve command. In the meantime, here are some existing threads that may help you:

Documentation:

Community-Help:

uncut wigeon
#

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
  },
})
clear iris
#

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