You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Formik的Yup校验规则中实现多值条件必填?

Fixing Yup Conditional Validation for Swift Code

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 is takes the current region value as an argument.
  • We use Array.includes() to check if that value is either 'Europe' or 'other'.
  • If the check returns true, the then block runs, making swiftCode required 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:52:52