React formik validationSchema 条件验证

React formik validationSchema conditionalValidation

基本上我想做的就是说如果 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'
                            ),
                    }),

你可以试试这个:

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;
});