gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:48:36 26 4
gpt4 key购买 nike

如果其他 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'] ])

More Details Check this link

关于reactjs - 是的 - 如何有条件地验证至少设置了 n 个值之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70785805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com