1
votes

I have a form with react-hooks-form and am trying to use yup validation. It works fine for now, but I am trying to make the field 'variant' required depending on the value of product[0].hasVrnts (variant should be required when hasVrnt===1). The schema object is:

const schema = yup.object().shape({
    date: yup.date().required(),
    beginDate: yup.date().required(),
    qty: yup.number().integer().positive(),
    product: yup.array().length(1).of(yup.object().shape({
        id: yup.number().integer().positive().required(),
        bom: yup.object({
            id: yup.number().integer().positive().required(),
            revId: yup.number().integer().positive().required(),
            code: yup.string(),
            name: yup.string()
        }),
        units: yup.array(),
        unitSet: yup.number().integer(),
        code: yup.string(),
        name: yup.string(),
        grp: yup.string(),
        hasVrnts: yup.number().integer()

    })).required(),

    variant: yup.array().length(1).of(yup.object().shape({
        id: yup.number().integer().positive(),
        code: yup.string(),
        name: yup.string(),
        unitSet: yup.number().integer(),
        units: yup.array(),
        recStats:yup.number().integer()
    })),
    rsrvd: yup.boolean() 
})

Thank you guys in advance.

1

1 Answers

0
votes

I think you may need to take a look at conditional validation in Yup. You can get it by using .when()

For example, you can apply different validation strategies of the field count depending on another field (isBig):

let schema = yup.object({
  isBig: yup.boolean(),
  count: yup.number().when('isBig', (isBig, schema) => {
    return isBig ? schema.min(5) : schema.min(0);
  }),
});

await schema.validate({ isBig: false, count: 4 });

It's described in the official docs of Yup: https://github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema