Avatar

Bonjour, I'm Julia.

Generating a Yup Validation Object with a Map Function

#forms #react #typescript #yup

2 min read

To follow on from Generating Multiple React useState Hooks For Multiple State Variables and since we're on the subject of validation with Yup (see my last post on Yup Validation for Date and Time With MomentJS), I wanted to write a quick note on how to generate a Yup validation object with a map function.

The place we got to with my previous example in Generating Multiple React useState Hooks For Multiple State Variables was a constant array like this.

const HOBBIES = [
  { question: 'How many times did you run?', stateName: 'running' },
  { question: 'How many manga comics did you read?', stateName: 'manga' },
  {
    question: 'How many hours did you spend on the drums?',
    stateName: 'drums',
  },
]

Using the same idea of first creating a parent object (validationObject), we can then map through our HOBBIES array and dynamically generate keys for this object. In my case I just wanted each of my radio button groups to be a required field.

export const validationSchema = (): FormValidationSchema => {
  const validationObject: { [key: string]: StringSchema } = {}

  // validation schema keys based on the name prop of the radio buttons in the form
  HOBBIES.forEach((hobby) => {
    validationObject[hobby.stateName] = Yup.string().required()
  })

  return Yup.object(validationObject)
}

© 2016-2024 Julia Tan · Powered by Next JS.