2021-10-30

Checking value of drop down is not in another drop down. Custom Validation using YUP

Im have 3 drop downs in a React Formik form, each with the same set of options. I want to provide some custom validation using YUP to ensure that each of these drop downs has a unique value selected.

The Formik values being set on each field take the shape of {id: somevalue, text: someText }

I have tried setting up my validation object as below:

const { values } = useFormikContext();

const validation = Yup.object({
    picker1: Yup.object()
        .test('test-name', 'Value must be Unique',
            function (value) {
                 return !((values["picker2"] && values["picker2"].id === value.id) ||
                (values["picker3"] && values["picker3"].id === value.id));
            }),
        ... repeat for other pickers
})

The problem I am having is that the formik value is always null for the pickers when the test function executes, presumably because the value of values is scoped to when the function is created. Is there a better way of attempting this as the documentation around custom validation in YUP seems a bit sparse.



from Recent Questions - Stack Overflow https://ift.tt/3jLYi5e
https://ift.tt/eA8V8J

No comments:

Post a Comment