Can't access formik.touched && formik.errors with Yup of internal property of an object

202 Views Asked by At

First timer...

I am using formik with yup form validation in react typescript and trying to get formik.touched && formik.errors for nested object .

whatever I tried not working

how should I get to the nested object ?

{formik.touched.address?.state && formik.errors.address?.state && ( <p className="text-danger">{formik.errors.address?.state}</p> )}


 validationSchema: yup.object({
      firstName: yup.string().required().min(2),
      lastName: yup.string().required().min(2),
      email: yup.string().required().email(),
      address: yup.object({
        country: yup.string().required().min(2),
        state: yup.string().min(2),      }),
     }),

return 
          <div className="form-floating col-6 mb-3 mt-3">
            <input
              type="text"
              className="form-control"
              id="floatingState"
              placeholder="John Doe"
              name="state"
              onChange={formik.handleChange}
              value={formik.values.address?.state}
              onBlur={formik.handleBlur}
            ></input>
            <label`your text` htmlFor="floatingState">State</label>
            {formik.touched.address?.state && formik.errors.address?.state && (
              <p className="text-danger">{formik.errors.address?.state}</p>
            )}
          </div>

2

There are 2 best solutions below

1
Usama On

First you need to set initialValues for address if you haven't

 initialValues={
        // other fields...
        address: {
          country: ''
          state: ''
        }
      }

And change value of name attribute of input to name="address.state", since state is inside address object.

0
zzbbq On

Input name should also be nested.

name="address.state"