How would one go about translating error messages that are returned by a field validate function?

default discord avatar
Jaaaaaay (DiddlySquat)
3 weeks ago
9

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?

  • discord user avatar
    jmikrut
    Payload Team
    3 weeks ago

    @dribbens

  • discord user avatar
    dribbens
    Payload Team
    3 weeks ago

    Oh yeah! I had this use-case in mind while building out the i18n support.



    You should have access to the translation function

    current language

    as a property in your custom validation function:

    t


    You 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-options


    Then in your validate function you can call and return it:


    return t('yourNamespace.yourErrorMessage');

  • default discord avatar
    Jaaaaaay (DiddlySquat)
    3 weeks ago

    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;
    };
  • discord user avatar
    jmikrut
    Payload Team
    3 weeks ago

    amazing

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.