node.js - 有条件地需要一个或另一个字段 - 是的
问题描述
我发现这解释起来有点复杂,并且没有找到任何解决方案。
我的架构中有 3 个字段。如果 field1 为 false,则需要 field2 OR field3。我试过这个,但它不工作:
const schema = Yup.object().shape({
field1: Yup.boolean().required(),
fiel2: Yup.array().when(['field1', 'field3'], {
is: (field1, field3) => !field1 && !field3,
then: Yup.array().required(),
otherwise: Yup.array(),
}),
field3: Yup.array().when(['field1', 'fiel2'], {
is: (field1, fiel2) => !field1 && !fiel2,
then: Yup.array().required(),
otherwise: Yup.array(),
}),
});
同样,如果 field1 为 false,则其他 2 个字段之一应该是必需的。
有什么解决办法吗?
解决方案
test
当它变得更复杂时,您可以使用:
yup.object().shape({
field1: yup.string(),
field2: yup.string().test({
test: function (value) {
const {field3, field1} = this.parent;
if (field1 && !field3) return value != null;
return true
}
}),
field3: yup.string().test({
test: function (value) {
const {field1, field2} = this.parent;
if (field1 && !field2) return value != null;
return true
}
})
});
推荐阅读
- python - 为python中的列表定义数值稳定的sigmoid函数的最佳方法
- css - 响应卡 bootstrap4
- powerbi - 用于合并的多列行的切片器
- javascript - 画布动画性能不佳,线条很多
- gcc - 为什么 x86-64 System V 调用约定在寄存器中传递 args 而不仅仅是堆栈?
- android - 如何在 Android 上使用 react native 查看所有待处理的推送通知?
- mysql - Chef MySQL 食谱用户创建错误
- android - Google Nearby Connections 2.0 功能
- python-3.x - 抓取收入数据
- react-native - Shoutem:克隆项目中特定于屏幕的数据保存在哪里?