sajad torkamani

Suppose you have a Formik form that contains a user field like this

{
  user: {
    name: 'Jim',
    age: 30,
  }
}

How can you take advantage of Formik’s support for using Yup with its validationSchema API to validate a user field like in the example above?

Here’s how:

import { Formik, Form, FormikProps } from 'formik'
import * as yup from 'yup'
import { Dump } from './Dump'
import { TextInput } from './TextInput'

interface FormValues {
  user: {
    name: string
    age: string
  }
}

const App: React.FC = () => {
  const validationSchema = yup.object().shape({
    user: yup.object().shape({
      name: yup.string().required(),
      age: yup.string().required()
    })
  })

  return (
    <div className="wrapper">
      <Formik
        initialValues={{
          user: {
            name: '',
            age: ''
          }
        }}
        validationSchema={validationSchema}
        onSubmit={() => {
          console.log('Form submitted.')
        }}
      >
        {({ values, errors }: FormikProps<FormValues>) => (
          <Form>
            <Dump title="Form values" value={values} />
            <Dump title="Form errors" value={errors} />

            <TextInput name="user.name" placeholder="Name" />
            <TextInput name="user.age" placeholder="Age" />
          </Form>
        )}
      </Formik>
    </div>
  )
}

export default App

CodeSandbox

Leave a comment

Your email address will not be published. Required fields are marked *