yup setLocale with i18n (and Formik)
See original GitHub issueI’m having some issues with setLocale and i18n (i’m using i18next, but that is not really relevant in this case) in the context of Formik forms.
I’m using a setLocale configuration like below:
setLocale({
mixed: {
default: 'forms.validation.invalid',
required: 'forms.validation.required'
},
string: {
min: ({ min, ...other }) => ({ transKey: 'forms.validation.minLength', values: { min } }),
max: ({ max }) => ({ transKey: 'forms.validation.maxLength', values: { max } })
}
});
Validations work fine, yup setLocale is doing it’s thing and returning strings and objects that are perfectly translatable. My point is where exactly do the translation.
My first attempt was translating the validation errors inside the form render, but that gives all kinds of issues (like detecting which validation message is already translated) and making the translated errors be used by the form.
Now I think I solved it by doing the translation inside setLocale. So instead of returning translation keys and objects with translation keys and other data (for interpolation purposes) I do it like this:
setLocale({
mixed: {
default: i18n.t('forms.validation.invalid'),
required: i18n.t('forms.validation.required')
},
string: {
min: ({ min }) => i18n.t('forms.validation.minLenght', { min }),
max: ({ max }) => i18n.t('forms.validation.maxLength', { max })
}
});
This seems to work fine, validation messages are translated and ready to be used inside formik so I guess this is a nice way of doing translations, but I’m wondering if there are any downsides to this approach because most info about i18n with yup seem to be handling translations inside the component itself.
Issue Analytics
- State:
- Created 4 years ago
- Comments:12 (5 by maintainers)
Top GitHub Comments
For anyone finding this now, the list of possible values can be seen at https://github.com/jquense/yup/blob/master/src/locale.ts
The problem with that approach is that you’re loading most of yup at bootstrap time, while validation is something you generally only need in very specific input scenarios and shouldn’t be in your main application bundle. Generally I think it’d be better to hook the loading of yup locales/translations to some sort of reused form component so they can be loaded on-demand.