How to validate objects inside objects with Yup/formik?

Asked

Viewed 2,464 times

2

I am using formik with Yup to handle my forms and need to validate two objects I have set in my initial formik values:

initialValues: {
  company: { company_name: '', cnpj: '', fantasy_name: '', state_registration: '' },
  user: { email: '', password: '' }
},
validationSchema: schema,

This is my validation schema Yup:

const schema = Yup.object().shape({
    company_name: Yup.string().required('Informe o nome da filial!'),
    cnpj: Yup.string().required('Informe o cnpj!'),
    email: Yup.string().email('Email não possui formato válido').required('Informe o e-mail'),
    password: Yup.string().required('Informe a senha')
  })

I would like to validate the properties within user/company, I tried something like:

company.company_name: Yup.string().required('Informe o nome da filial!')

But I get:

Parsing error: Unexpected token, expected ","

How can I do that?

1 answer

3


Just use Yup.object().shape() inside the property. Something like this:

import * as Yup from 'yup';

const schema = Yup.object().shape({
  user: Yup.object().shape({
    email: Yup.string()
      .email()
      .required(),
    password: Yup.string().required()
  }),

  company: Yup.object().shape({
    company_name: Yup.string().required(),
    cnpj: Yup.string().required(),
    fantasy_name: Yup.string().required(),
    state_registration: Yup.string().required()
  })
});

See a demonstration here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.