【问题标题】:Yup schema generator for form array and nested form groups using Formik, Material-UI - React是的,使用 Formik,Material-UI - React 的表单数组和嵌套表单组的模式生成器
【发布时间】:2021-02-20 07:07:52
【问题描述】:

我有一个 yup 模式生成器,用于生成 yup 模式,它工作正常,但在处理表单数组和嵌套表单组时失败。

是的架构生成器

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;
}

我的表单结构示意图

"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"
              ]
           ]
        }
     }
  ]
 }
}

如何为 Formik 数组和嵌套表单组动态实现 yup 架构。

提前致谢

【问题讨论】:

    标签: reactjs forms material-ui formik yup


    【解决方案1】:

    您应该使用循环调用来使其适用于数组和对象。

    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])
     );
    }
    

    【讨论】:

    • 这可能行不通,但我只是想向您介绍代码的基本外观。此外,您可能需要更改数据结构以使其变得简单。
    猜你喜欢
    • 2020-11-19
    • 2021-10-07
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    相关资源
    最近更新 更多