2

I am trying to use react-intl to create a localized validation schema with yup. However, all I could find is integration with i18n. I am using react-intl already as my main localization tool; therefore, I would like to stay with this tool. Is it possible to create a functioning localization with react-intl for yup? I am creating validation schemas in a separate files FYI.

Thanks for any tips

CodeSandbox Example of the issue

TLDR: I need to localize the validation message using. react-intl. At the moment I am not sure how to pass the localization id and get it translated in the render component.

1 Answers1

6

You just only return the key of the translation message in the schema. and in your render method, you can only translate that key......

My solution:

export const schema = yup
  .object({
    simpleInput: yup.string().required("form.required.message")
  })
  .required();

Create util like:

function getTranslate(key) {
  return intl.formatMessage(key);
}

and last thing, for the TextField we just use:

<TextField
   {...field}
   error={!!error}
   helperText={error ? getTranslate(error) : null}
/>
Anh Le
  • 270
  • 1
  • 9
  • Coule you please give me an example? As I mentioned I am creating the schema in a separate file and importing it. Then I pass the schema in to the react hook for resolver. I don’t see a way to translate the key of the translation message inside of the render method. – Le Tuan Anh Feb 20 '22 at 13:04
  • Could you create a Sanbox or Stackbliz and describe your issue there? that could be nice to solve your issue soon. – Anh Le Feb 20 '22 at 13:05
  • Hello, sorry it took a while to create the issue. This is the link to the code replica in codesandbox [link](https://codesandbox.io/s/hopeful-stallman-2l9x06?file=/src/App.js) – Le Tuan Anh Feb 20 '22 at 13:41
  • Hi, I think I get your answer now. The react-hook-form controller returns the error message. Instead of displaying it right away, I just need to pass the message into the int.formatMessage param that will act like the id. Thank you so much – Le Tuan Anh Feb 20 '22 at 14:02