我有一个这样的数据结构:
{
"subject": "Ah yeah",
"description": "Jeg siger...",
"daysOfWeek": [
{
"dayOfWeek": "MONDAY",
"checked": false
},
{
"dayOfWeek": "TUESDAY",
"checked": false
},
{
"dayOfWeek": "WEDNESDAY",
"checked": true
},
{
"dayOfWeek": "THURSDAY",
"checked": false
},
{
"dayOfWeek": "FRIDAY",
"checked": false
},
{
"dayOfWeek": "SATURDAY",
"checked": true
},
{
"dayOfWeek": "SUNDAY",
"checked": true
}
],
"uuid": "da8f56a2-625f-400d-800d-c975bead0cff",
"taskSchedules": [],
"isInitial": false,
"hasChanged": false
}
在 daysOfWeek
中,我希望确保至少有一项具有 checked: true
。
这是迄今为止的验证模式(但不起作用):
const taskValidationSchema = Yup.object().shape({
subject: Yup.string().required('Required'),
description: Yup.string(),
daysOfWeek: Yup.array()
.of(
Yup.object().shape({
dayOfWeek: Yup.string(),
checked: Yup.boolean(),
})
)
.required('Required'),
taskSchedules: Yup.array(),
})
有没有可能验证 daysOfWeek
的值,并确保其中至少有一个值的 checked: true
?
setTimeout
这个东西真是让我开心极了 :-) 使用arrayHelper
时出现了非常奇怪的行为。非常感谢。 - Klauswhen()
条件中引用(例如)description
,并将其应用于(例如)dayOfWeek
?基本上...dayOfWeek: Yup.string().when("description", {is: ..., then: ...}
但是它无法从数组内部工作。 - KaMZaTacompact()
,表单数据也会被过滤。这意味着在验证后的表单数据中,数组将只包含真值。解决方案是使用test()
进行自定义验证。test('atLeastOne', '错误消息', days => days.some(day => day.checked))
- SajithK