如何在Formik的Yup校验规则中实现多值条件必填?
Hey there! I spot the exact issue with your current Yup setup—let's get that conditional validation working for your swiftCode field.
The Problem with Your Current Code
Your line is: 'Europe' || 'other' doesn't work the way you think it does. In JavaScript, the || operator returns the first "truthy" value it encounters. So here, 'Europe' || 'other' evaluates directly to 'Europe', meaning your validation only triggers when region is exactly 'Europe'—it ignores 'other' entirely.
The Fix
Instead of using a logical OR, you can pass a function to the is property. This function will receive the current value of the region field, and you can check if it's in your target list of values:
swiftCode: Yup.string().when('region', { is: (regionValue) => ['Europe', 'other'].includes(regionValue), 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' ), }),
How This Works
- The function passed to
istakes the currentregionvalue as an argument. - We use
Array.includes()to check if that value is either'Europe'or'other'. - If the check returns
true, thethenblock runs, makingswiftCoderequired and validating its format.
Your routeCode validation is already set up correctly since it only checks for a single value ('USA'), but this function approach works great for multiple conditional values like your swiftCode case.
内容的提问来源于stack exchange,提问作者ChrisJnr Potgieter

