Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

501
Views
Multiple layers of yup form validation - React and yup

I have the below datastructure and am struggling validating the config array of objects that needs to be sent off when form is submitted. I am using ReactJS and yup form validation with Formik.

Form Data structure:

values = 
    {
    "name": "test",
    "description": "desc",
    "type": {
        "value": 1,
    },
    "config": [
        {
            "grade": "A",
            "threshold": "1.0"
        },
        {
            "grade": "B",
            "threshold": "2.0"
        },
    ]
}
  1. The config fields are required when my select (dropdown) type == 1 or type == 2, i have this working for a simple formfield as

description: yup.string().when("type", { is: (type) => type.value ===1 || type.value ===2, then: yup.string().required("Description required for type 1 or 2"), otherwise: yup.string().notRequired()})

  1. Config comes in pairs of grade: and threshold: so you can't just have one, e.g. "config": [ { "grade": "A" } ] is incorrect. whereas "config": [ { "grade": "A", "threshold": "1.0" }] is correct.

it needs both grade and threshold. I already have yup validation for checking both fields (grade+threshold) are submitted and not just one.

screenshot showing grade and threshold fields

Here is my yup form validation so far:

     config: yup.array().of(
    yup.object().shape(
      {
        grade: yup.string().when("threshold", {
          is: (threshold) => threshold !== undefined,
          then: yup.string().required(
          "If a threshold is entered, a grade is also required"),
          otherwise: yup.string().notRequired(),
        }),
        threshold: yup.number().when("label", {
          is: (grade) => grade !== undefined,
          then: yup
            .number()
            .typeError('score threshold must be a number')
            .required(
              "If a grade is entered, a threshold is also required"
            ),
          otherwise: yup.number().notRequired(),
        }),
      },
      ["threshold", "grade"]
    )
  )
});

So essentially, i now need to add the check to make the config fields required if the dropdown select is type 1 or 2 and not sure how to do this.

Help appreciated. Thanks!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!