如何使用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
相关产品推荐
相关产品推荐

