Reputation: 648
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
Upvotes: 1
Views: 961
Reputation: 2152
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])
);
}
Upvotes: 1