Verified Solution

[StackOverflow/reactjs] Formik passing context to yup validation

Sponsored Content
### ROOT CAUSE The issue arises because the `context` passed to the validation function is not being properly provided by Formik. Formik does not automatically pass context to the validation function unless explicitly specified. The validation function expects the context to be provided via the `validationContext` prop in the Formik component. ### CODE FIX Pass the context to the Formik component using the `validationContext` prop and ensure the validation function accepts the context as its second argument. **Example:** ```jsx import { useFormik } from 'formik'; import * as yup from 'yup'; const validationSchema = (data, context) => { return yup.object().shape({ field: yup.string().required(context.requiredMessage), }); }; const MyForm = () => { const formik = useFormik({ initialValues: { field: '' }, validationSchema, validationContext: { requiredMessage: 'This field is required' } }); return (
{formik.errors.field &&
{formik.errors.field}
}
); }; ``` **Explanation:** - The `validationContext` prop in the Formik component provides the context object to the validation function. - The validation function must accept two arguments: `data` (the form values) and `context` (the passed context object).
Deploy on DigitalOcean ($200 Credit)

Related Fixes

[StackOverflow/kubernetes] Is Kgateway an Envoy fork?
[microsoft/vscode] double click on number not always selecting entire word
[StackOverflow/python] How to solve exceptions raised by the GlobalDossierApplication.objects.get() method?