Yup validation with dynamic keys in an object
Asked Answered
B

1

9

I have an object for validation that might look like this:

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

The keys of the entries object are dynamic (uuids). I want to validate that the name property in any of those objects is not an empty string. However, entries is not required, it is only required that if there are any entries, they cannot contain an empty string. How can I do this with Yup?

const exampleObjectValidation = Yup.object().shape({
  foo: Yup.object({
    entries: Yup.object({
      /* what goes here ? */
   })
  })
})
Bradney answered 17/8, 2022 at 15:42 Comment(1)
See this particular commentGeometry
B
10

Here's how I did it:

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

          return Yup.object().shape(newEntries)
        }
        return Yup.mixed().notRequired()
      }),
    }),
  })
  .nullable()
  .notRequired()
Bradney answered 17/8, 2022 at 18:18 Comment(1)
is there a way to validate the key format using this method?Bagworm

© 2022 - 2024 — McMap. All rights reserved.