From 96f417bee52c29003bbc37b2b8ea298533264aa9 Mon Sep 17 00:00:00 2001 From: codeflorist <41453547+codeflorist@users.noreply.github.com> Date: Mon, 9 Jun 2025 22:33:10 +0200 Subject: [PATCH] docs: add info about localized/built-in validation error messages (#12718) i couldn't find this documented in the docs, but only via a forum post (https://payloadcms.com/community-help/discord/how-would-one-go-about-translating-error-messages-that-are-returned-by-a-field-validate-function). this might be rather useful for multilanguage admin panels or to simply re-use payload's build in error messages. --- docs/fields/overview.mdx | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/fields/overview.mdx b/docs/fields/overview.mdx index 802c5e0e62..aedba5f5df 100644 --- a/docs/fields/overview.mdx +++ b/docs/fields/overview.mdx @@ -305,6 +305,22 @@ The following additional properties are provided in the `ctx` object: | `req` | The current HTTP request object. Contains `payload`, `user`, etc. | | `event` | Either `onChange` or `submit` depending on the current action. Used as a performance opt-in. [More details](#async-field-validations). | +#### Localized and Built-in Error Messages + +You can return localized error messages by utilizing the translation function provided in the `req` object: + +```ts +import type { Field } from 'payload' + +export const MyField: Field = { + type: 'text', + name: 'myField', + validate: (value, {req: { t }}) => Boolean(value) || t('validation:required'), // highlight-line +} +``` + +This way you can use [Custom Translations](https://payloadcms.com/docs/configuration/i18n#custom-translations) as well as Payload's built in error messages (like `validation:required` used in the example above). For a full list of available translation strings, see the [english translation file](https://github.com/payloadcms/payload/blob/main/packages/translations/src/languages/en.ts) of Payload. + #### Reusing Default Field Validations When using custom validation functions, Payload will use yours in place of the default. However, you might want to simply augment the default validation with your own custom logic.