如何使用动态点表示法字段名称创建YUP模式?以下架构无效。我如何动态地遍历Costs.0.item,Costs.1.item,Costs.2.item和Costs.0.amount,Costs.1.amount,Costs.2.amount?任何帮助表示赞赏!
const IpSchema = Yup.object().shape({
Project_Title: Yup.string()
.min(2, 'Too Short!')
.max(255, 'Too Long!')
.required('Required'),
Costs.0.item: Yup.string()
.min(2, 'Too Short!')
.max(255, 'Too Long!')
.required('Required'),
Costs.1.item: Yup.string()
.min(2, 'Too Short!')
.max(255, 'Too Long!')
.required('Required'),
Costs.2.item: Yup.string()
.min(2, 'Too Short!')
.max(255, 'Too Long!')
.required('Required'),
Costs.0.amount: Yup.string()
.min(2, 'Too Short!')
.max(255, 'Too Long!')
.required('Required'),
Costs.1.amount: Yup.string()
.min(2, 'Too Short!')
.max(255, 'Too Long!')
.required('Required'),
Costs.2.amount: Yup.string()
.min(2, 'Too Short!')
.max(255, 'Too Long!')
.required('Required'),
});
答案 0 :(得分:2)
如果将YUP
与formik
一起使用,则可以选中this。在docs提供的示例中。而根据docs的其他说法,您可以这样做:
const IpSchema = Yup.object().shape({
Project_Title: Yup.string()
.min(2, 'Too Short!')
.max(255, 'Too Long!')
.required('Required'),
Costs: Yup.array().of(
Yup.object()
.shape({
item: Yup.string()
.min(2, 'Too Short!')
.max(255, 'Too Long!')
.required('Required'),
amount: Yup.string()
.min(2, 'Too Short!')
.max(255, 'Too Long!')
.required('Required')
})
),
});
答案 1 :(得分:1)
在这种情况下,您必须使用yup.array
,即:
const IpSchema = Yup.object().shape({
Project_Title: Yup.string()
.min(2, 'Too Short!')
.max(255, 'Too Long!')
.required('Required'),
Costs: Yup.array().of(
Yup.object({
item: Yup.string()
.min(2, 'Too Short!')
.max(255, 'Too Long!')
.required('Required')
amount: Yup.string()
.min(2, 'Too Short!')
.max(255, 'Too Long!')
.required('Required')
})
),
});