Create dynamic Yup validation schema from JSON

后端 未结 1 1148
攒了一身酷
攒了一身酷 2021-02-13 21:23

I\'m trying to use Yup along with Formik in my react form. The form fields are going to be dynamic so as their validations.

export con         


        
1条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-13 22:12

    In case someone is trying to create yupschema on the fly. With some help, I was able to do it.

    import * as yup from "yup";
    
    export function createYupSchema(schema, config) {
      const { id, validationType, validations = [] } = config;
      if (!yup[validationType]) {
        return schema;
      }
      let validator = yup[validationType]();
      validations.forEach(validation => {
        const { params, type } = validation;
        if (!validator[type]) {
          return;
        }
        console.log(type, params);
        validator = validator[type](...params);
      });
      schema[id] = validator;
      return schema;
    }
    

    Codesandbox

    0 讨论(0)
提交回复
热议问题