Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup doesn't work properly with i18n

I have this piece of a code. I want to add error messages depending on user's locale, but yup throws errors, same if fields are filled in incorrectly

[missing "en.login.emailRequiredError" translation] [missing "en.login.passRequiredError" translation]

const schema = yup.object().shape({
  email: yup
      .string()
      .email(i18n.t('login.emailSpellError'))
      .required(i18n.t('login.emailRequiredError')),
  password: yup
      .string()
      .matches(/^((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15})$/i, i18n.t('login.passSpellError'))
      .required(i18n.t('login.passRequiredError')),
});

i18n.t('login.passRequiredError') works fine when I put it into a render method for checking it but it does not work with the yup. Any suggestions? Thanks in advance

like image 547
user7245021 Avatar asked Mar 20 '18 16:03

user7245021


2 Answers

In your schema, replace:

.email(i18n.t('login.emailSpellError'))

with

.email('login.emailSpellError')

then in your render method:

{t(`form.errors.${form.errors.email}`)}

This assumes your translation file has an entry like this:

"form": { "errors": {"login": {"emailSpellError": "Your email is invalid"}}}}

The goal here is to move the t() method into your render method and have all translations happen there.

like image 165
Mark Carlson Avatar answered Sep 18 '22 13:09

Mark Carlson


Yup Validation method,

// You define the key mentioned in the translation file, in my example 'Invalid email' and 'Required'  

    let ForgotPasswordSchema = yup.object().shape({
      email: yup.string().email('Invalid email').required('Required'),
    });

In render method,

// As per your definition

isInvalid={(!!errors.email) && this.context.t(!!errors.email)}
invalidText={(errors.email) && this.context.t(errors.email)}

Translation File

export const translations = {
  "cy": {
    "Required":"Gofynnol",
    "Invalid email":"Nid yw'r cyfeiriad ebost yn ddilys",
}
 };  
like image 42
Jacob Joy Avatar answered Sep 20 '22 13:09

Jacob Joy