Formik + Yup: How to immediately validate form on mount?
Asked Answered
A

3

11

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!

Analiese answered 19/5, 2020 at 3:38 Comment(0)
B
24

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].

Beefy answered 19/5, 2020 at 17:4 Comment(2)
Best answer I have found! Thanks!Northing
Thanks I was missing the validateOnMount fieldHeigho
M
1

There's a prop called isInitialValid. Setting it to false solved my problem :)

Mufinella answered 5/2, 2023 at 6:58 Comment(0)
S
-1

you can use errors and touched props, like this

<Formik 
    initialValues={initialValues} 
    validationSchema={validation} 
    validateOnMount 
> 
    {props => { 
        const { errors, touched } = props 
        return ( 
            <Form> 
                ... 
                {errors.field && touched.field ? <Error>{errors.field}</Error> : null} 
                ... 
            </Form> 
        )
    }
</Formik>
Straightedge answered 19/5, 2020 at 3:51 Comment(1)
Yeah, I show errors but only when touched the field. How can I see errors before this? Thank you!Analiese

© 2022 - 2024 — McMap. All rights reserved.