反应formik验证模式条件验证

时间:2020-09-22 11:23:39

标签: reactjs validation formik yup

基本上,我要说的是,如果region =“ Europe”或“ other”,则必须填写该字段 ,确实通过了formik文档,但没有找到任何东西。 也是formik的新手,所以不知道这是否是一个nube问题 确实为is属性尝试了一个数组,但仍然很迷失

<Formik
                enableReinitialize={true}
                initialValues={{
                    name: currentBankData.name || '',
                    address: currentBankData.address || '',
                    country: currentBankData.country || '',
                    region: currentBankData.region || '',
                    city: currentBankData.city || '',
                    swiftCode: currentBankData.swiftCode || '',
                    routeCode: currentBankData.routeCode || '',
                }}
                validationSchema={Yup.object().shape({
                    name: Yup.string().min(3).required('Name is required.'),
                    address: Yup.string().required('Address is required.'),
                    country: Yup.string().required('Country is required.'),
                    region: Yup.string().required('Region is required.'),
                    city: Yup.string().required('City is required.'),

                    swiftCode: Yup.string().when('region', {
                        is: 'Europe',      //Would like to do something like this 'Europe' || 'other, but  
                                                     doesnt work :)

                        then: Yup.string()
                            .required('SwiftCode is required.')
                            .matches(
                                /[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?/i,
                                'This is not the correct Swift Code'
                            ),
                    }),

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

Yup.string().when("region", (region, schema) => {
  return ["Europe", "other"].includes(region)
    ? schema.required().matches(
                            /[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?/i,
                            'This is not the correct Swift Code'
                        )
    : schema;
});