jquense / yup

Dead simple Object schema validation
MIT License
22.93k stars 934 forks source link

How to validate a dynamic object key and its shape using the lazy method #2129

Closed jtomasrl closed 12 months ago

jtomasrl commented 1 year ago

Im trying to validate an object that can have dynamic keys, named itineraryN, where N can be a number from 0 to 99., something like this (yes, it has to be a dictionary)

{
   itineraries: {
      itinerary1: {
        value: string().required()
      },
      itineraryN: {
        value: string().required()
      }
  }
}

At the same time, I want to make validation to the object shapes inside the itineraryN key.

This is what I've done so far, but I can seem to find a way to validate the keys (currentValue). I was thinking on adding a regex expression (new RegExp(/^itinerary[0-9]{1,2}$/)) inside the reduce, but Im not sure how to make the validation invalid from there.

itineraries: lazy((values) => {
    const newEntries = Object.keys(values).reduce(
      (accumulator, currentValue) => {
        return ({
          ...accumulator,
          [currentValue]: object({
            value: string().required()
          }).noUnknown(messages.NO_UNKNOWN),
        })
      },
      {},
    )
    return object().shape(newEntries)
  }),
jquense commented 12 months ago

add a custom test to your object that checks the keys

object().shape(newEntries).test('keys, ...)