0

I'm trying to set up a validation schema using Yup for a form that has two conditional fields: page_id and custom_link. The requirement is that one of these fields must be provided. If one is filled, the other can be null or empty.

Here is the schema I've created:

import * as yup from 'yup';

const validationSchema = yup.object().shape({
    title: yup.string().required(t('form.validation.required')).max(125, t('form.validation.max')),
    code: yup.string().required(t('form.validation.required')).max(125, t('form.validation.max')),
    page_id: yup.mixed().when('custom_link', {
        is: (custom_link) => !custom_link || custom_link.length === 0,
        then: () => yup.mixed().required(t('form.validation.required')),
        otherwise: () => yup.mixed()
    }),
    custom_link: yup.mixed().nullable().when('page_id', {
        is: (page_id) => !page_id || page_id.length === 0,
        then: () => yup.mixed().required(t('form.validation.required')),
        otherwise: () => yup.mixed()
    })
},
[ [ 'page_id', 'custom_link' ] ]
);

export default validationSchema;

I've tried various combinations and adjustments but can't seem to get it right.

Could someone point out what I'm doing wrong or suggest an alternative approach to achieve this kind of conditional validation with Yup?

Any help would be greatly appreciated!

0

Browse other questions tagged or ask your own question.