fix: use req.t for the ValidationError message when t is not passed
ValidationError only translated its "The following field is invalid" prefix when a t function was passed as the second argument, otherwise it used the English strings. Errors thrown from hooks with just req were always shown in English in the admin toast. The constructor now falls back to req.t when t is not passed, before using the English strings.
This commit is contained in:
1 parent
e3da300e8e
commit
5f07976a1f
2 files changed
+26
-2
No files matched your search
@@ -0,0 +1,22 @@
|
||||
import { initI18n } from '@payloadcms/translations'
|
||||
import { de } from '@payloadcms/translations/languages/de'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { ValidationError } from './ValidationError.js'
|
||||
|
||||
describe('ValidationError', () => {
|
||||
it('should translate the message with req.t when no t is passed', async () => {
|
||||
const i18n = await initI18n({
|
||||
config: { fallbackLanguage: 'de', supportedLanguages: { de } },
|
||||
context: 'api',
|
||||
language: 'de',
|
||||
})
|
||||
|
||||
const error = new ValidationError({
|
||||
errors: [{ message: 'Invalides Passwort', path: 'password' }],
|
||||
req: { i18n, t: i18n.t },
|
||||
})
|
||||
|
||||
expect(error.message).toBe('Das folgende Feld ist nicht korrekt: password')
|
||||
})
|
||||
})
|
||||
@@ -37,13 +37,15 @@ export class ValidationError extends APIError<{
|
||||
id?: number | string
|
||||
/**
|
||||
* req needs to be passed through (if you have one) in order to resolve label functions that may be part of the errors array
|
||||
* and to translate the message when `t` is not passed
|
||||
*/
|
||||
req?: Partial<PayloadRequest>
|
||||
},
|
||||
t?: TFunction,
|
||||
) {
|
||||
const message = t
|
||||
? t('error:followingFieldsInvalid', { count: results.errors.length })
|
||||
const translate = t ?? results.req?.t
|
||||
const message = translate
|
||||
? translate('error:followingFieldsInvalid', { count: results.errors.length })
|
||||
: results.errors.length === 1
|
||||
? en.translations.error.followingFieldsInvalid_one
|
||||
: en.translations.error.followingFieldsInvalid_other
|
||||
|
||||
Reference in new issue
Block a user