英文:
YUP validation on nested object with possible no or more properties
问题
我试图在这个对象上进行yup验证:
placements: {
3: {},
5: {},
6: {0: 'D17'},
7: {},
8: {},
9: {},
10: {},
11: {},
}
问题是,例如3: {}可以为空,这是完全可以的!
但是,如果它有一个键和值,它应该检查字符串不为空/长度> 0
我尝试了很多可能的解决方案,但没有任何有效的。
该对象用于保存从leaflet地图中的放置,如果嵌套对象为空,那没问题,但如果嵌套对象中有一个键,如6: {0: 'D17'},则值应该大于0,因为它将初始化为6: {0: ''}或6:{0: '', 1: '', 2: ''}。我们不知道有多少键和值。
这是我现在的代码,但根本不起作用:
placements: Yup.object()
.required("必须选择位置")
.test("is-valid", "必须选择至少一个位置", (placements) =>
Object.values(placements).some((placement: { number: string }) => {
return Object.values(placement).some((p) => p !== "");
})
),
英文:
I'm trying to make a yup validation on this object:
placements: {
3: {},
5: {},
6: {0: 'D17'},
7: {},
8: {},
9: {},
10: {},
11: {},
}
The problem is that for example 3: {} could be empty and that is perfectly fine!
But IF it has a kay&value is should check that the string is not empty/length > 0
I have tried so many possible solutions without anything that works.
The object is for saving placements from a leaflet map, if the nested object is empty that is OK, but if the nested object has a key like in 6: {0: 'D17'} the value should be longer than 0 because it will be initialized as 6: {0: ''} or 6:{0: '', 1: '', 2: ''}. We dont know how many key&values it has.
This is the code i have now and its not working at all..
placements: Yup.object()
.required("Plassering må velges")
.test("is-valid", "Minst en plassering må velges", (placements) =>
Object.values(placements).some((placement: { number: string }) => {
return Object.values(placement).some((p) => p !== "");
})
),
答案1
得分: 1
问题是some
在空数组上始终返回false
:
console.log([].some(() => true));
因此,您必须添加另一个使用||
(或)的检查:
placements: Yup.object()
.required("Plassering må velges")
.test("is-valid", "Minst en plassering må velges", (placements) =>
Object.keys(placements).length === 0 || Object.values(placements).some((placement: { number: string }) => {
return Object.values(placement).some((p) => p !== "");
})
),
其中检查应该是一种检查对象是否为空的方式。在这里,我使用Object.keys
并检查长度是否为0(表示没有键)。
英文:
The problem is that some
always returns false
on an empty array:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
console.log([].some(() => true));
<!-- end snippet -->
So you'll have to add another check with ||
(OR):
placements: Yup.object()
.required("Plassering må velges")
.test("is-valid", "Minst en plassering må velges", (placements) =>
Object.keys(placements).length === 0 || Object.values(placements).some((placement: { number: string }) => {
return Object.values(placement).some((p) => p !== "");
})
),
where the check should be some way of checking that the object is empty. Here I'm using Object.keys
and checking if the length is 0 (meaning there are no keys).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论