首页
/ Yup库中自定义数组验证方法在条件验证中的使用限制

Yup库中自定义数组验证方法在条件验证中的使用限制

2025-05-08 08:01:44作者:平淮齐Percy

问题背景

在使用Yup进行表单验证时,开发者经常会遇到需要自定义验证逻辑的情况。Yup提供了addMethod功能,允许开发者扩展内置的验证方法。然而,当这些自定义方法与条件验证(when方法)结合使用时,可能会出现预期之外的行为。

自定义数组验证方法的实现

在Yup中,我们可以通过addMethod为数组类型添加自定义验证方法。以下是一个检查数组是否排序的验证方法实现:

declare module 'yup' {
  interface ArraySchema<TIn extends any[] | null | undefined, TContext, TDefault = undefined, TFlags extends yup.Flags = ''> 
    extends yup.Schema<TIn, TContext, TDefault, TFlags> {
    isArraySorted(): ArraySchema<TIn, TContext, TDefault, TFlags>;
  }
}

addMethod(array, "isArraySorted", function isArraySorted() {
  return this.test("isArraySorted", "-", function (values) {
    if (!Array.isArray(values)) {
      return this.createError({
        path: this.path,
        message: "Type不是数组",
      });
    }
    for (let i = 0; i < values.length; i += 1) {
      if (values?.[i + 1] && values[i] >= values?.[i + 1]) {
        return this.createError({
          path: this.path,
          message: "数组未排序",
        });
      }
    }
    return true;
  });
});

条件验证中的问题

当这个自定义方法直接使用时,它能正常工作:

const schema = yup.object({
  optsA: yup.boolean().required(),
  optsB: yup.object({
    list: yup.array().of(yup.number()).isArraySorted(),
  }),
});

但当尝试在条件验证(when方法)中使用时,验证方法不会被调用:

const schema = yup.object({
  optsA: yup.boolean().required(),
  optsB: yup.object({
    list: yup.array()
      .of(yup.number())
      .when([
        "optsA",
        {
          is: true,
          then: (schema) => schema.isArraySorted(),
        },
      ]),
  }),
});

问题原因分析

经过调查,发现这个问题与Yup的条件验证作用域有关。在Yup中,when方法默认只能访问同级或父级的字段值。在上述例子中,optsB.list试图访问其祖父级的optsA字段,这超出了Yup默认的作用域范围。

解决方案

方案一:调整数据结构

将相关字段放在同一层级,确保它们在相同的作用域内:

const schema = yup.object({
  optsB: yup.object({
    optsA: yup.boolean().required(),
    list: yup.array()
      .of(yup.number())
      .when([
        "optsA",
        {
          is: true,
          then: (schema) => schema.isArraySorted(),
        },
      ]),
  }),
});

方案二:使用上下文传递值

在更复杂的场景中,可以通过Yup的上下文(context)机制传递需要的值:

const schema = yup.object({
  optsA: yup.boolean().required(),
  optsB: yup.object({
    list: yup.array()
      .of(yup.number())
      .when('$optsA', {
        is: true,
        then: (schema) => schema.isArraySorted(),
      }),
  }),
});

// 使用时传递上下文
schema.validate(value, { context: { optsA: true } });

最佳实践建议

  1. 保持验证逻辑简洁:尽量避免跨多层级访问字段值
  2. 合理组织数据结构:将相关的验证条件放在同一层级
  3. 充分测试:对条件验证逻辑进行充分测试,确保各种边界情况都能正确处理
  4. 考虑使用上下文:对于复杂的跨层级验证,考虑使用上下文机制

总结

Yup的条件验证功能强大但有其作用域限制。理解这些限制并合理组织验证逻辑,可以避免自定义验证方法在条件验证中失效的问题。通过调整数据结构或使用上下文机制,开发者可以灵活地实现各种复杂的验证需求。

登录后查看全文
热门项目推荐
相关项目推荐