Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

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

default discord avatar
Jaaaaaay (DiddlySquat)last year
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
    last year

    @dribbens

  • discord user avatar
    dribbens
    last year

    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)last year

    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
    last year

    amazing

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team..