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

当applyToAll未选中且两数组为空时,用Yup显示MUI Autocomplete错误

解决Yup联动验证:未选applyToAll时Categories/Products至少填一个的问题

原代码的核心问题是在Yup的test方法里直接使用yup.ref()做长度比较——yup.ref()返回的是字段引用对象,不是实际数组的长度值,所以没法直接用> 0判断。要实现两个字段的联动验证,需要借助test方法的第二个参数上下文来获取整个表单的取值,再做逻辑判断。

修正后的验证方案如下:

import { TFunction } from 'i18next';
import * as yup from 'yup';

export const getValidationSchema = (t: TFunction) => yup.object({
  applyToAll: yup.boolean(),
  categories: yup.array().when('applyToAll', {
    is: false,
    then: yup.array().test({
      message: t('promo.categories.required', { ns: 'validations' }),
      test: function (categories) {
        // 通过上下文获取products字段的当前值
        const products = this.parent.products;
        // 只要categories或products有一个非空,验证就通过
        return (categories?.length || 0) > 0 || (products?.length || 0) > 0;
      }
    }),
  }),
  products: yup.array().when('applyToAll', {
    is: false,
    then: yup.array().test({
      message: t('promo.products.required', { ns: 'validations' }),
      test: function (products) {
        // 通过上下文获取categories字段的当前值
        const categories = this.parent.categories;
        // 只要products或categories有一个非空,验证就通过
        return (products?.length || 0) > 0 || (categories?.length || 0) > 0;
      }
    }),
  }),
});

关键改动说明:

  • 改用普通函数作为test的回调(而非箭头函数),这样可以通过this.parent访问整个表单的所有字段值(箭头函数会绑定外部this,无法获取Yup的上下文)
  • 分别获取另一个字段的取值,判断两个数组的长度是否至少有一个大于0
  • 用|| 0处理数组为undefined的情况,避免读取length时报错

这样修改后就能实现需求中的联动效果:

  • 未选中applyToAll时,只有当categories和products都为空时才会触发对应字段的错误提示
  • 添加分类后,products的错误会自动消失;添加产品后,categories的错误也会自动消失
  • 选中applyToAll时,两个字段的验证规则会被跳过,错误自动清除

内容的提问来源于stack exchange,提问作者tdimoff

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:52:12