DEV Community

Cover image for Sending validation errors through a Formik form
Alex
Alex

Posted on • Originally published at buaiscia.github.io

Sending validation errors through a Formik form

When we need to validate a Formik form (often with Yup) we can use the following method: validateForm.
It returns a promise so we have to check if it resolves or not.
However, the validation errors are sent directly inside the promise as an argument and not caught. So the promise is always resolved in this case.

To pass the validation error, then, we have to pass the errors as an argument of the promise itself.

  formik.validateForm({...})
    .then((errors) => submit(formik, values, errors))
Enter fullscreen mode Exit fullscreen mode

Then the errors can be checked and the logic can be written in the submit method.

const submit = (formik, values, errors) => {...}
Enter fullscreen mode Exit fullscreen mode

Bonus: here are the types (for TS users) for the 3 arguments above:

formik: FormikContextType<FormikValues>
values: FormikValues
errors: FormikErrors<FormikValues>
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, and let's connect on Twitter!

Top comments (0)