I'm currently writing some validate functions and would like to give the user specific messages on what went wrong.
What is the recommended way of…
a) retrieving the currently selected locale of the user
…and…
b) give them localized error messages?
Oh yeah! I had this use-case in mind while building out the i18n support.
You should have access to the translation function
as a property in your custom validation function:
tYou will have to extend the translations to have your custom error message.
The docs here show how you're supposed to do that:
https://payloadcms.com/docs/configuration/i18n#configuration-optionsThen in your validate function you can call and return it:
return t('yourNamespace.yourErrorMessage');
Awesome, thanks guys! will give it a try asap
Works like a charm, thanks again!
For future reference:
export const validateURLField: Validate<string> = async (
value: string,
{ t }
) => {
try {
const url = new URL(value);
} catch (err) {
return t("shared:errors:url:invalid");
}
return true;
};amazing
Hello it's a little late but payload 3.0 implemented this a little bit different:
export const validateURLField: Validate = async (value: string, { req: { t } }) => {
try {
const url = new URL(value)
} catch (err) {
return t('shared:errors:url:invalid')
}
return true
}
When creating our own endpoints, should we add validation with zod it or rely on the created underlying models and do validation and localization of errors over there? What is your opinion on this? What is the current payload team idea on this? I diddnt find anything online yet
Star
Discord
online
Get dedicated engineering support directly from the Payload team.