是的-如何有条件地验证是否设置了n个值中的至少一个



如果其他3个字段中有1个不为空,如何使用Yup验证使字段成为强制性字段?我尝试了以下模式,但遇到了循环依赖问题。非常感谢。

const schema = yup.object().shape({
a: yup.string().when(['b', 'c', 'd'], {
is: (b, c, d) => !b && !c && !d,
then: yup.string().required()
}),
b: yup.string().when(['a', 'c', 'd'], {
is: (a, c, d) => !a && !c && !d,
then: yup.string().required()
}),
c: yup.string().when(['a', 'b', 'd'], {
is: (a, b, d) => !a && !b && !d,
then: yup.string().required()
}),
d: yup.string().when(['a', 'b', 'c'], {
is: (a, b, c) => !a && !b && !c,
then: yup.string().required()
})
}, [['a', 'b', 'c'], ['b', 'c', 'd'], ['a','c', 'd'], ['a','b','d']])

希望下面的代码能解决您的问题

/* 
All you need to do is list all the pair-wise (2-tuples) combinations. 
As you have 4 fields, you expect to have 6 pairs in your array. 
i.e. ['a', 'b'],['a', 'c'],['a', 'd'], ['b', 'c'], ['b', 'd'],['c', 'd'])
*/
const schema = yup.object().shape({
a: yup.string().when(['b', 'c', 'd'], {
is: (b, c, d) => b || c || d,
then: Yup.string(),
otherwise: Yup.string().required('Required')
}),
b: yup.string().when(['a', 'c', 'd'], {
is: (a, c, d) => a || c || d,
then: Yup.string(),
otherwise: Yup.string().required('Required')
}),
c: yup.string().when(['a', 'b', 'd'], {
is: (a, b, d) => a || b || d,
then: Yup.string(),
otherwise: Yup.string().required('Required')
}),
d: yup.string().when(['a', 'b', 'c'], {
is: (a, b, c) =>  a || b || c,
then: Yup.string(),
otherwise: Yup.string().required('Required')
})
}, [['a', 'b'],['a', 'c'],['a', 'd'], ['b', 'c'], ['b', 'd'],['c', 'd'] ])

更多详细信息查看此链接

您可以这样做:a: yup.string().when(['b', 'c', 'd'], { is: (...fields) => fields.some((field) => field === true), then: yup.string().required() }),

你可以使用JS的函数,但我选择了"some"来检查数组中是否至少有一个项符合条件,这相当于你的检查——如果数组中没有一个项为true,那就和所有项都为false一样。

顺便问一下,依赖项数组的作用是什么?[['a', 'b', 'c'], ['b', 'c', 'd'], ['a','c', 'd'], ['a','b','d']])我认为Yup官方文档中没有提到它(至少我知道,如果有原因的话,我会很高兴得到更新,谢谢(。

最新更新