gpt4 book ai didi

javascript - 动态创建 Yup 嵌套对象模式

转载 作者:行者123 更新时间:2023-11-29 15:55:58 26 4
gpt4 key购买 nike

对于这个“平面”对象验证

const fields = [
{label: 'Name', name: 'name', validation: yup.string().required()},
{label: 'City', name: 'city', validation: yup.string().required()},
{label: 'Phone', name: 'phone'},
]

我创建了 createYupSchema 函数来从 fields 中获取 Yup 架构对象。

const createYupSchema = (fields ) => {
const schema = fields.reduce((schema, field) => {
return field.validation
? {...schema, [field.name]: field.validation}
: schema
}, {})

return yup.object().shape(schema)
}

输出是 Yup 对象:

yup.object().shape({
name: yup.string().required(),
city: yup.string().required(),
})

但我也有可能在 fields

中使用嵌套对象
const fields = [
{label: 'Name', name: 'name', validation: yup.string().required()},
{label: 'Address', name: 'address.city', validation: yup.string().required()},
{label: 'Phone', name: 'phone'},
]

所以 Yup 对象应该是:

yup.object().shape({
name: yup.string().required(),
address: yup.object().shape({
city: yup.string().required()
}),
})

是否可以从字段创建这种类型的 Yup 对象?

最佳答案

我解决了我的问题。现在 createYupSchema 以这种方式工作

const createYupSchema = fields => {
const schema = fields.reduce((schema, field) => {
const isObject = field.name.indexOf(".") >= 0;

if (!field.validation) {
return schema;
}

if (!isObject) {
return { ...schema, [field.name]: field.validation };
}

const reversePath = field.name.split(".").reverse();
const currNestedObject = reversePath.slice(1).reduce((yupObj, path) => {
return { [path]: yup.object().shape(yupObj) };
}, {[reversePath [0]]: field.validation});

return { ...schema, ...currNestedObject };
}, {});

return yup.object().shape(schema);
};

关于javascript - 动态创建 Yup 嵌套对象模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57928271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com