Search code examples
reactjsformikyup

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!


Solution

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