0

Basicaly all I want to do is say is if region = "Europe" or "other" then the field is required , did go through the formik documentation but not finding anything. Am also new to formik so dont know if this is a nube question or not Did try an array for the is property but am still very lost

<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'
                            ),
                    }),
ChrisJnr Potgieter
  • 141
  • 1
  • 2
  • 13

1 Answers1

1

You can try this:

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;
});
CD..
  • 72,281
  • 25
  • 154
  • 163