首页 > 解决方案 > React formik 验证Schema conditionalValidation

问题描述

基本上我想做的就是说如果 region = "Europe" 或 "other" 那么该字段是必需的,确实通过了 formik 文档但没有找到任何东西。我也是 formik 的新手,所以不知道这是否是一个问题

<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'
                            ),
                    }),

标签: reactjsvalidationformikyup

解决方案


你可以试试这个:

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

推荐阅读