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!
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
},
})
@ritsu thanks for the help, went with the option you suggested in the code snippet, worked like a charm 🍻
Star
Discord
online
Get dedicated engineering support directly from the Payload team.