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

使用Yup验证数组无重复项:自定义.test方法失效求助

Yup数组去重验证问题解决方案

你的这种验证规则写法是完全可行的,自定义.test不生效通常是逻辑错误或错误绑定问题,以下是具体排查和修复方案:

1. 修正验证逻辑

确保你的重复检查逻辑正确,以下是标准的id去重验证代码:

const validationSchema = Yup.object().shape({
  myArray: Yup.array()
    .of(
      Yup.object().shape({
        id: Yup.string().required('Select ID'),
      })
    )
    .test('is-unique', 'Duplicate selected', function (value) {
      // 空数组/空值时直接通过验证
      if (!value || value.length === 0) return true;
      // 提取所有id
      const ids = value.map(item => item.id);
      // 通过Set去重后对比长度判断是否有重复
      return new Set(ids).size === ids.length;
    })
})

2. 手动指定错误路径(可选但更可靠)

如果直接返回false仍不显示错误,可以用this.createError明确指定错误绑定的字段路径:

.test('is-unique', 'Duplicate selected', function (value) {
  if (!value || value.length === 0) return true;
  const ids = value.map(item => item.id);
  const hasDuplicates = new Set(ids).size !== ids.length;
  
  if (hasDuplicates) {
    return this.createError({
      path: 'myArray', // 绑定到数组字段
      message: 'Duplicate selected'
    });
  }
  return true;
})

3. 确认错误提示的渲染位置

因为这个验证是加在数组字段myArray上的,所以错误提示需要渲染在数组对应的容器位置,而不是单个数组元素的输入框下方。比如在React表单中,要确保获取到myArray字段的错误信息并展示。

4. 验证触发时机检查

确认表单提交时是否触发了整个schema的验证,比如使用validationSchema.validate(formValues, { abortEarly: false }),确保数组层面的验证被执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 22:48:20