Wondering where is the best way to validate during create/update that the combination of two field values is unique across all collection entries and fail validation if they are not.
The CollectionConfig type doesn't have a validate function, but I can see a
beforeValidate
hook that I might be able to use? I suppose I'd have to query all collection entries inside that hook to properly validate and throw an error if it fails. Am I on the right track, or is there a better way? Thanks!
I suppose another option would be to make a unique compound index in MongoDB. It works but I'd like to be able to give a clearer validation error message if possible.
beforeValidate is the proper place to do this type of logic.
Any field data you need should be inside
data
or
originalDoc
that is passed.
https://payloadcms.com/docs/hooks/collections#beforevalidate
You should be able to throw one of the errors available in
payload/errors
if validation fails.
Thanks for confirming! Are the
payload/errors
documented anywhere?
Sharing back my
beforeValidate
hook implementation in case anyone needs to solve a similar problem:
async ({ data, originalDoc }) => {
const payload = await getPayloadClient();
const entries = (
await payload.find({
collection: 'myCollection',
pagination: false,
where: { id: { not_equals: originalDoc?.id } },
})
).docs;
entries.forEach(entry => {
if (entry.field1 === data?.field1 && entry.field2 === data?.field2) {
throw new ValidationError([
{ field: 'field1', message: 'This combination of field 1 and field 2 already exists.' },
{ field: 'field2', message: 'This combination of field 1 and field 2 already exists.' },
]);
}
});
}
I don't believe their usage is documented explicitly. Your best bet is to search the monorepo for
from 'payload/errors'
to see some examples.
I figured it out for my use case, but might be something to consider adding to the docs. Here's the path to errors in the source code for anyone else that might find it useful:
https://github.com/payloadcms/payload/tree/main/packages/payload/src/errorsStar
Discord
online
Get dedicated engineering support directly from the Payload team..