yup: SetLocale is not working as expected - Instance/Babel problem

Problem

I’m trying to use the function setLocale and It’s not translating the errors. The problem seems to be with the library instance, some babel configuration or import problem.

When I use setLocale and return the same instance of yup to my validation files It does work as expected.

Scenario

Should work like this. Right? index.js

import { setLocale } from 'yup';

setLocale({
  mixed: {
    required: 'Preencha esse campo para continuar'
  },
  string: {
    email: 'Preencha um e-mail válido',
    min: 'Valor muito curto (mínimo ${min} caracteres)',
    max: 'Valor muito longo (máximo ${max} caracteres)'
  },
  number: {
    min: 'Valor inválido (deve ser maior ou igual a ${min})',
    max: 'Valor inválido (deve ser menor ou igual a ${max})'
  }
});

personal-data-validations.js

import * as yup from 'yup';

const PersonalDataSchema = yup.object().shape({
  fullName: yup.string().min(5).max(70).required()
});

export { PersonalDataSchema };

The workaround

I created a index to my validations -> validations.js and export yup from there. After that I imported the yup instance from my validations index and now It’s working.

validations.js

import * as yup from 'yup';

yup.setLocale({
  mixed: {
    required: 'Preencha esse campo para continuar'
  },
  string: {
    email: 'Preencha um e-mail válido',
    min: 'Valor muito curto (mínimo ${min} caracteres)',
    max: 'Valor muito longo (máximo ${max} caracteres)'
  },
  number: {
    min: 'Valor inválido (deve ser maior ou igual a ${min})',
    max: 'Valor inválido (deve ser menor ou igual a ${max})'
  }
});

export default yup;

personal-data-validations.js

import yup from 'validation';

const PersonalDataSchema = yup.object().shape({
  fullName: yup.string().min(5).max(70).required()
});

export { PersonalDataSchema };

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 84
  • Comments: 17 (1 by maintainers)

Most upvoted comments

you need to set the locale before you import yup elsewhere. schema constructed before you use setLocale will have the old values

If anyone has this problem using TypeScript you have to define all your schemas as a function that takes yup, for example:

import * as yup from 'yup';

export default (y: typeof yup) =>
  y
    .string()
    .email()
    .max(300);

Pass yup (import * as yup from 'yup') to your schemas after calling setLocale on it.

Hi ! Having the same problem, I use this work around (probably not better) :

// webpack.config.js
const { NormalModuleReplacementPlugin } = require('webpack');

module.exports = {
    ...,
    plugins: [
        new NormalModuleReplacementPlugin(
            /yup\/lib\/locale\.js/,
            path.resolve(process.cwd(), './src/utils/custom-yup-locale.js'),
        ),
   ]
}

It will replace locale.js of yup by your custom locales

I know this issue is closed but the error still happens. I’ve handled it by delaying the main code execution:

import { registerRootComponent } from 'expo'
import { initLocale } from './src/Schemas' // Method where 'setLocale' is called

const loadApp = async () => {
  const App = await import('./src/App')

  registerRootComponent(App.default)
}

initLocale()
loadApp()

There may be better ways to handle this but it worked for me and may also help someone else.

I had the same problem.

After some research, I found the cause was because the module actually using yup (in your case, personal-data-validations.js) was being imported before the line of code calling setLocale (in your case, that line is in index.js) was run, so yup saw the original locale.

Your workaround works because, by explicitly importing the module containing setLocale (validation.js) in the module actually using yup (personal-data-validations.js), you make sure setLocale is always run before yup is actually being used.

Another possible way around I could think of is to wrap yup.object(…) in a function, say, createPersonalDataSchema(), and then make sure that function is called after setLocale.

For me setLocale is not working at all. Here is the sandbox: https://codesandbox.io/s/jj8zzp2mn5 Any clue on this?

@Rockson You are setting the locale to number but trying to validade a string. Correct the types and it works.