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

如何使用Yup验证含动态键的对象至少包含一个键?

解决方案

你可以通过给emails字段添加校验规则,确保动态键对象至少包含一个有效键。结合你的场景,推荐两种可行方式:

方式一:用object.min()约束属性数量

直接在lazy返回的对象校验规则上添加min(1),指定对象至少要有1个属性:

import { object, lazy, string, number, mapValues } from 'yup';

const propertySchema = object({
    emails: lazy(obj => {
        return object(
            mapValues(obj, () => object({
                email: string().required(),
                token: string().required(),
                tokenExpiresAt: number().integer().positive()
            }))
        ).min(1, 'emails至少需要包含一个邮箱条目');
    })
})

方式二:添加自定义test校验

如果需要更灵活的提示信息或逻辑,给emails字段单独加自定义测试:

import { object, lazy, string, number, mapValues } from 'yup';

const propertySchema = object({
    emails: lazy(obj => {
        return object(
            mapValues(obj, () => object({
                email: string().required(),
                token: string().required(),
                tokenExpiresAt: number().integer().positive()
            }))
        )
    }).test('has-at-least-one-key', 'emails不能为空对象', value => {
        return Object.keys(value || {}).length > 0;
    })
})

验证效果与注意事项

  • 执行propertySchema.validateSync(user1)时,会因emails为空对象抛出错误,验证失败。
  • 执行propertySchema.validateSync(user2)时,会通过验证,符合预期。
  • 注意修正原代码中user2的语法错误(属性间缺少逗号):
const user2 = {
  emails: {
    "some@mail.de": {
      email: 'some@mail.de',
      token: 'abcd',
      tokenExpiresAt: 4712
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 18:05:17