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

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

本文介绍了是的:在对象数组中进行深度验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据结构:

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
}

daysOfWeek中,我要确保至少一个项目具有checked: true.

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

是否可以验证daysOfWeek的值,以确保其中至少一个具有checked: true?

Is it possible to validate the values of daysOfWeek ensuring that at least one of them has checked: true?

推荐答案

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

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

并采用以下形式:

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

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

这篇关于是的:在对象数组中进行深度验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:56