Deepak Negi
Deepak Negi

Reputation: 331

How to get current form values in the schema validation in Formik? (possibly using reference)

I have recently upgraded Formik from v1 to v2. I was using schema validation using yup to validate the values, and in one case I am passing a function to validate as below:

const formikRef = useRef()

const SomeSchema = yup
    .object()
    .shape({
        fieldA: yup.string(),
        fieldB: yup
            .number()
            .test(
                'do-validation for fieldB',
                'error message for fieldB if validation fails',
                (fieldB) => {
                    // fieldB here is the current value of field fieldB
                    // here I want to access the value of fieldA
                    // previously, I was using formikRef.current.state.values
            })
    })


<Formik
    // other props
    validationSchema={SomeSchema}
    ref={formikRef}
>

I have tried passing innerRef instead of ref as mentioned in the documentation. But, mine are custom fields so probably that is why it is not working. I am not sure how to get all the current values of the form?

Upvotes: 2

Views: 1206

Answers (1)

Stephen Clark
Stephen Clark

Reputation: 68

You can use this.parent

fieldB: yup
    .number()
    .test(
        'do-validation for fieldB',
        'error message for fieldB if validation fails',
        function(fieldB) => {
            const {fieldA} = this.parent;
            console.log(fieldA);
        }
    )

Or for arrow functions

fieldB: yup
    .number()
    .test(
        'do-validation for fieldB',
        'error message for fieldB if validation fails',
        (fieldB, context) => {
            const {fieldA} = context.parent;
            console.log(fieldA);
        }
    )

Upvotes: 3

Related Questions