0

I'm creating a React app and I want to use react-localize-redux for translation and yup for validation. My problem is in understanding how to combine them.

I know that I can either pass strings to yup-require or a function, as this is the signature:

mixed.required(message?: string | function): Schema

This works perfectly when I just pass a string, but I don't get it how I then can pass a translation of my react-localize-redux after importing the

import { Translate } from 'react-localize-redux';

module, where I'm used to JSX components like

<Translate id="you-can-login-now" />

which returns my translated string then. I have totally no idea..

My code:

import { Translate } from 'react-localize-redux';
import * as Yup from 'yup';
<Formik
          initialValues={this.state.data}
          validationSchema={Yup.object().shape({
            name: Yup.string().required('required')
          })}
...
/>
Tom
  • 111
  • 1
  • 8

1 Answers1

1

Let me give some advice, in my case I don't use package for localization or translation, but I use function setLocale from Yup itself. I hope this work for you too. First, I create file javascript for dictionary message like this.

src/validators/setLocaleID.js

    exports.mixed = {
      default: '${path} tidak valid',
      required: 'Bidang ${path} harus diisi',
      oneOf: '${path} harus mengandung salah satu dari nilai berikut: ${values}',
      notOneOf: '${path} tidak dapat mengandung nilai-nilai berikut: ${values}'
    };
    module.exports = exports

and then I create validation schema

src/validators/addUser.js

    import * as Yup from 'yup'
    import localeID from './setLocaleID.js'

    Yup.setLocale(localeID)

    export default Yup.object().shape({
      name: Yup.string()
        .required()
    })

lastly, I import it, in my view component like this.

src/views/AdminForm.jsx

import AddUserSchema from 'validators/addUser'

    .
    .
    .
    <Formik
                enableReinitialize={true}
                initialValues={userData}
                validationSchema={AddUserSchema}
                onSubmit={(values, { setSubmitting }) => {
                  this.handleSaveUser(values)
                  setSubmitting(false)
                }}
              > 
    .
    .

I already try this way, and I hope it's a similar solution for you.

Iwan Firmawan
  • 125
  • 1
  • 3
  • 12