For this "flat" object validation
const fields = [
{label: 'Name', name: 'name', validation: yup.string().required()},
{label: 'City', name: 'city', validation: yup.string().required()},
{label: 'Phone', name: 'phone'},
]
I created createYupSchema
function to get Yup schema object from fields
.
const createYupSchema = (fields ) => {
const schema = fields.reduce((schema, field) => {
return field.validation
? {...schema, [field.name]: field.validation}
: schema
}, {})
return yup.object().shape(schema)
}
The output is Yup object:
yup.object().shape({
name: yup.string().required(),
city: yup.string().required(),
})
But I would to have the possibility to use also nested object in fields
const fields = [
{label: 'Name', name: 'name', validation: yup.string().required()},
{label: 'Address', name: 'address.city', validation: yup.string().required()},
{label: 'Phone', name: 'phone'},
]
So the Yup object should be:
yup.object().shape({
name: yup.string().required(),
address: yup.object().shape({
city: yup.string().required()
}),
})
Is it possibile to create this type of Yup object from fields
?