yup.js 在条件下检查数组

Tzo*_*Noy 1 javascript testing validation yup

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

只有当标志为真时,我才想检查对象数组。

所以:

{
  shouldCheck: false
}
Run Code Online (Sandbox Code Playgroud)

这应该通过

{
  shouldCheck: true
}
Run Code Online (Sandbox Code Playgroud)

这应该打破

{
  shouldCheck: true,
  rules: []
}
Run Code Online (Sandbox Code Playgroud)

这应该打破

{
  shouldCheck: true,
  rules: [1]
}
Run Code Online (Sandbox Code Playgroud)

这应该打破

{
  shouldCheck: true,
  rules: [{other: 'xx'}]
}
Run Code Online (Sandbox Code Playgroud)

这应该打破

{
  shouldCheck: true,
  rules: [right: 'one']
}
Run Code Online (Sandbox Code Playgroud)

这应该通过

是的架构:

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()
  }),
});
Run Code Online (Sandbox Code Playgroud)

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

小智 6

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

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()
  }),
});
Run Code Online (Sandbox Code Playgroud)