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

如何为带可选参数的返回字符串函数字段构建Joi v14验证

为TypeScript的Toy类型构建Joi 14 Schema验证

针对你需要验证的Toy类型:

type Toy = {
  id: string;
  codeName: (nameFormat?: string) => string;
  price: number;
}

Joi 14本身没有原生支持验证函数的参数类型和返回类型,需要通过Joi.func()结合自定义验证逻辑来实现codeName字段的校验。以下是完整的schema实现:

const toySchema = Joi.object({
  id: Joi.string().required(),
  codeName: Joi.func()
    .required()
    .custom((value, helpers) => {
      // 验证无参数调用时返回string
      try {
        const result = value();
        if (typeof result !== 'string') {
          return helpers.error('any.invalid');
        }
      } catch (err) {
        return helpers.error('any.invalid');
      }

      // 验证传入string参数时返回string
      try {
        const result = value('test-format');
        if (typeof result !== 'string') {
          return helpers.error('any.invalid');
        }
      } catch (err) {
        return helpers.error('any.invalid');
      }

      return value;
    }, 'codeName function validation'),
  price: Joi.number().required()
});

关键逻辑说明

  1. 基础校验:Joi.func().required()确保codeName是必填的函数类型。
  2. 自定义验证:通过.custom()添加运行时校验:
    • 无参数调用函数,检查返回值是否为string,调用报错则判定无效。
    • 传入string类型参数调用函数,同样检查返回值类型和调用是否正常。
  3. 错误提示:自定义验证的第二个参数是错误标识,方便定位问题。

测试示例

// 验证通过的对象
const validToy = {
  id: 'toy-1',
  codeName: (nameFormat?: string) => nameFormat ? `toy-${nameFormat}` : 'toy-default',
  price: 99.99
};
console.log(toySchema.validate(validToy).error); // undefined

// 返回非string的无效对象
const invalidToy1 = {
  id: 'toy-2',
  codeName: () => 123,
  price: 50
};
console.log(toySchema.validate(invalidToy1).error?.message); // 验证失败

// 不接受string参数的无效对象
const invalidToy2 = {
  id: 'toy-3',
  codeName: (num: number) => `toy-${num}`,
  price: 30
};
console.log(toySchema.validate(invalidToy2).error?.message); // 验证失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:26:09