问题
I have a data structure like this:
{
"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
}
In daysOfWeek
I want to ensure that at least one of the items has checked: true
.
This is my validation schema so far (but not working):
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(),
})
Is it possible to validate the values of daysOfWeek
ensuring that at least one of them has checked: true
?
回答1:
I solved it using compact()
(filtering out falsey values) together with setTimeout
after the FieldArray modifier function:
const validationSchema = Yup.object().shape({
subject: Yup.string().required(i18n.t('required-field')),
description: Yup.string(),
daysOfWeek: Yup.array()
.of(
Yup.object().shape({
dayOfWeek: Yup.string(),
checked: Yup.boolean(),
})
)
.compact(v => !v.checked)
.required(i18n.t('required-field')),
taskSchedules: Yup.array(),
})
And in form:
<Checkbox
value={day.dayOfWeek}
checked={day.checked}
onChange={e => {
replace(idx, { ...day, checked: !day.checked })
setTimeout(() => {
validateForm()
})
}}
/>
来源:https://stackoverflow.com/questions/59197551/yup-deep-validation-in-array-of-objects