Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formik + Yup: How to immediately validate form before submit?

I want to show field errors when form mounted. Not after submit.

Yup:

const validation = Yup.object().shape({
  field: Yup.string().required('Required')
});

Formik:

<Formik
  initialValues={initialValues}
  validationSchema={validation}
  validateOnMount
>
  ...
</Formik>

Thanks for help!

like image 930
Nurhat Kosumov Avatar asked May 19 '20 03:05

Nurhat Kosumov


People also ask

Why does Formik touch all fields before submit?

Why does Formik touch all fields before submit? It is common practice to only show an input's errors in the UI if it has been visited (a.k.a "touched"). Before submitting a form, Formik touches all fields so that all errors that may have been hidden will now be visible.


1 Answers

The simple answer is

Pass initialTouched to Formik which will be an object with key of the fields you want to show the error message and the value true for those keys.

e.g.

<Formik
  initialValues={initialValues}
  initialTouched={{ 
    field: true,
  }}
  validationSchema={validation}
  validateOnMount
>
  ...
</Formik>

But there is alot of ways to do this, but you can create an component that call validateForm on the initial render

const ValidateOnMount = () => {
    const { validateForm } = useFormikContext()

    React.useEffect(() => {
        validateForm()
    }, [])

    // the return doesn't matter, it can return anything you want
    return <></>
}

You can also do the same using validateOnMount and setting initialTouched to true on all fields you want to display the error message (maybe you only want to show certain field's error message on the initial mount).

<Formik 
    validateOnMount
    initialValues={initialValues}
    validationSchema={validation}
    initialTouched={{ 
        field: true
    }}
    {...rest}
>
</Formik>

Where initialTouched should be an object that have keys to all fields that you want to validate that are in initialValues but with the value true, which means you already touched that field.


Another way to do this is only passing validateOnMount to Formik and display any error message without checking for touched[name].
If you use ErrorMessage from formik, it won't work because it checks for touched[name] === true to display the message, so you need to create your own way of displaying the error, but only checking for errors[name].

like image 106
Vencovsky Avatar answered Nov 15 '22 07:11

Vencovsky