是的:在对象数组中进行深度验证

时间:2019-12-05 14:41:49

标签: formik yup

我有这样的数据结构:

{
  "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

1 个答案:

答案 0 :(得分:0)

我在FieldArray修改器函数之后使用compact()(过滤掉虚假值)和setTimeout来解决了这个问题:

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(),
})

并采用以下形式:

<Checkbox
  value={day.dayOfWeek}
  checked={day.checked}

  onChange={e => {
    replace(idx, { ...day, checked: !day.checked })
    setTimeout(() => {
      validateForm()
    })
  }}
/>