简体   繁体   中英

Yup schema generator for form array and nested form groups using Formik, Material-UI - React

I have an yup schema generator for generating yup schema which is working fine but fails when it comes to handling Form Arrays and Nested Form Groups.

Yup Schema Generator

const createYupSchema = (schema, config)=> {
  if (config.validation) {
    const { validationType, validations = [] } = config.validation;
    if (!yup[validationType]) {
      return schema;
    }
    let validator = yup[validationType]();
    validations.forEach((validation) => {
    const { params, type } = validation;
    if (!validator[type]) {
      return;
    }
    validator = validator[type](...params);
  });
   schema[config.props.name] = validator;
  }
 return schema;
}

schema of my form structure

"addressType":{
  "props":{
    "name":"addressType",
    "label":"Address type:",
    "type":"radio"
   },
  "value":"workPlace",
  "validation":{
    "validationType":"string",
    "validations":[
      {
        "type":"required",
        "params":[
           "Address is required"
        ]
      }
    ]
   }
 },
"students":{
  "props":{
    "name":"students"
  },
  "fields":{
    "studentName":{
     "name":"studentName",
     "type":"text",
     "label":"student name"
    },
  "age":{
     "name":"age",
     "type":"number",
     "label":"Age"
    }
 },
"validation":{
  "name":"students",
  "validationType":"array",
  "validations":[
     {
        "studentName":{
           "validations":[
              "type":"required",
              "params":[
                 "StudentName is required"
              ]
           ]
        }
     }
  ]
 }
}

How can I achieve yup schema dynamically for Formik Array and nested Form Groups.

Thanks in Advance

You should use a recurring call to make it work for array and object.

if (validation.type === 'array' || validation.type === 'object') {
 const innerSchema = createYupSchema({}, {
    props: { name: 'key' },
    validations: validation.validations
 });
 validator = yup.array().of(
    yup.object().shape(innerSchema[key])
 );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM