Nurhat Kosumov
Nurhat Kosumov

Reputation: 113

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

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!

Upvotes: 11

Views: 19504

Answers (3)

Yair Ohana
Yair Ohana

Reputation: 11

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

Upvotes: 1

Vencovsky
Vencovsky

Reputation: 31605

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

Upvotes: 24

caiopsilva
caiopsilva

Reputation: 19

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>

Upvotes: -1

Related Questions