Tzook Bar Noy
Tzook Bar Noy

Reputation: 11677

yup.js check array when condition

I have an object with a flag as boolean and another item as array of objects.

I would like to check the array of objects only if the flag is true.

So:

{
  shouldCheck: false
}

this should pass

{
  shouldCheck: true
}

this should break

{
  shouldCheck: true,
  rules: []
}

this should break

{
  shouldCheck: true,
  rules: [1]
}

this should break

{
  shouldCheck: true,
  rules: [{other: 'xx'}]
}

this should break

{
  shouldCheck: true,
  rules: [right: 'one']
}

this should pass

yup schema:

const delaySchema = yup.object().shape({
  shouldCheck: yup.boolean(),
  rules: yup.mixed()
    .when(['shouldCheck'], {
      is: (sck) => {
        return sck;
      },
    then: yup.array().of(yup.object().shape({
      right: yup.string().required(),
    })),
    otherwise: yup.mixed().nullable()
  }),
});

now the problem here is that it ignores the internal value and dont check them.

Upvotes: 1

Views: 21181

Answers (1)

try to use yup.array() before condition

const delaySchema = yup.object().shape({
  shouldCheck: yup.boolean(),
  rules: yup.array()
    .when(['shouldCheck'], {
      is: (sck) => {
        return sck;
      },
    then: yup.array().of(yup.object().shape({
      right: yup.string().required(),
    })),
    otherwise: yup.mixed().nullable()
  }),
});

Upvotes: 7

Related Questions