How do you Create a Formik YUP Schema with Dynamic Field Names?

隐身守侯 提交于 2020-03-25 13:47:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!