diff --git a/services/frontend/src/utils/forms.ts b/services/frontend/src/utils/forms.ts index ccff7ff..af22bf6 100644 --- a/services/frontend/src/utils/forms.ts +++ b/services/frontend/src/utils/forms.ts @@ -1,5 +1,5 @@ import lodash from "lodash"; -import { number } from "yup"; +import { toaster } from "."; export const checkArray = (array: any, name: string): T => { if (!Array.isArray(array)) { @@ -195,3 +195,22 @@ export const packArrayAsStrings = ( ) ); }; + +/** + * Formik is configured to validate fields automatically using Yup. + * The problem is Formik does not call `onSubmit` function when errors + * are present. Therefore, a work around was to call `formik.submitForm` + * after showing errors to the user. The `reportErrorsAndSubmit` utility + * function basically implements this. + */ +export const reportErrorsAndSubmit = (formik: any) => () => { + const errors = Object.entries(formik.errors); + if (errors.length > 0) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + for (const [_field, message] of errors) { + toaster(message as string, "error"); + } + } else { + formik.submitForm(); + } +};