【问题标题】:Yup validation with dynamic keys in an object是的,使用对象中的动态键进行验证
【发布时间】:2022-08-18 02:18:23
【问题描述】:

我有一个可能看起来像这样的验证对象:

const exampleObject = {
  foo: {
    entries: {
      \'785bac64-c6ce-4878-bfb8-9cf5b32e2438\': {
        name: \'First object\',
      },
      \'117450da-315b-4676-ad23-edd94a4b6b51\': {
        name: \'Second object\',
      },
    },
  },
}

entries 对象的键是动态的 (uuids)。我想验证任何这些对象中的 name 属性不是空字符串。但是,entries 不是必需的,只有在存在时才需要任何条目,它们不能包含空字符串。我怎么能用 Yup 做到这一点?

const exampleObjectValidation = Yup.object().shape({
  foo: Yup.object({
    entries: Yup.object({
      /* what goes here ? */
   })
  })
})

标签: javascript forms validation object yup


【解决方案1】:

这就是我的做法。

import { isEmpty } from 'lodash'

const validationSchema = Yup.object()
  .shape({
    foo: Yup.object({
      entries: Yup.lazy((value) => {
        if (!isEmpty(value)) {
          const newEntries = {}
          const dynamicKey = Object.keys(value).toString()
          const validationObject = {
            name: Yup.string().required('Item cannot be empty'),
          }
          newEntries[dynamicKey] = Yup.object(validationObject)

          return Yup.object().shape(newEntries)
        }
        return Yup.mixed().notRequired()
      }),
    }),
  })
  .nullable()
  .notRequired()

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 2014-01-02
    • 2022-07-21
    • 2019-11-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2019-07-31
    相关资源
    最近更新 更多