问题
How do you create a YUP schema with dynamic dot notation field names? The below schema is not valid. How would I iterate through Costs.0.item, Costs.1.item, Costs.2.item AND Costs.0.amount, Costs.1.amount, Costs.2.amount dynamically? Any help is appreciated!
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'),
});
回答1:
If you use YUP
with formik
you can check this. On docs provided example. And otherwhise according docs you can do it like this:
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')
})
),
});
回答2:
You have to use yup.array
in that case, i.e.:
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')
})
),
});
来源:https://stackoverflow.com/questions/60307058/how-do-you-create-a-formik-yup-schema-with-dynamic-field-names