首页 > 解决方案 > yup.js 条件时检查数组

问题描述

我有一个对象,其标志为布尔值,另一个项目为对象数组。

我只想在标志为真时检查对象数组。

所以:

{
  shouldCheck: false
}

这应该通过

{
  shouldCheck: true
}

这应该打破

{
  shouldCheck: true,
  rules: []
}

这应该打破

{
  shouldCheck: true,
  rules: [1]
}

这应该打破

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

这应该打破

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

这应该通过

是的架构:

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()
  }),
});

现在这里的问题是它忽略了内部值并且不检查它们。

标签: javascriptvalidationtestingyup

解决方案


尝试使用是的。条件前的数组()

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()
  }),
});

推荐阅读