0
votes

formik v1.5.2, yup v0.27.0, react v16.8.6

I can't make Yup validation work in Formik with an array of objects. The code is on the codesandbox https://codesandbox.io/s/kw1r49v25o?fontsize=14

The initial values:

const INITIAL_VALUES = {
  users: [
    {
      value: "admin"
    }
  ]
};

The Yup schema:

const usersSchema = Yup.object().shape({
  users: Yup.array().of(
    Yup.object().shape({
      value: Yup.string()
        .max(3)
        .required()
    })
  )
});

I intentionally limited string size to 3 chars to fire the validation error.

The component:

function App() {
  const [data, setData] = useState(INITIAL_VALUES);
  useEffect(() => {
    setData({
      users: [
        {
          value: "trex"
        },
        {
          value: "velociraptor"
        }
      ]
    });
  }, []);

  return (
    <div className="App">
      <Formik
        initialValues={data}
        enableReinitialize={true}
        validateOnChange={true}
        validateSchema={usersSchema}
        render={({ values, errors, touched, isValid, isValidating }) => {
          console.log("render - isValid", isValid);
          console.log("render - isValidating", isValidating);
          console.log("render - errors", errors);
          return (
            <Form>
              <Field name="users[0].value" />
              <div>{`isValid = ${isValid}`}</div>
              {Object.keys(errors) > 0 ? (
                <div>{`Error: ${JSON.stringify(errors)}`}</div>
              ) : null}
            </Form>
          );
        }}
      />
    </div>
  );
}

And there are no errors on the page. I expect to see the stringified error(s) and isValid = false when I add new chars in the input.

1

1 Answers

2
votes

Your Yup schema is correct, it's just the prop name is not. It should be validationSchema not validateSchema.

Note that since you don't have a field for users[1] the form will never be valid as it is now (because "velociraptor" is more than three characters). But you may be aware of that already and just set the example up this way.