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

如何使用Middy在Serverless AWS Lambda中验证年份字段为4位?

解决Middy中JSON Schema验证年份为4位数字的问题

你遇到的问题是因为length是JSON Schema中仅针对字符串类型的验证关键字,对数字类型不生效。要实现年份必须是4位数字的约束,需要用数字类型的专属验证规则:

  • 将year的类型从number更改为integer(年份是整数,更精准)
  • 使用minimum和maximum限定数值范围,确保年份在1000到9999之间(包含边界)

修改后的inputSchema代码如下:

const inputSchema = {
  type: "object",
  properties: {
    body: {
      type: "object",
      properties: {
        year: { 
          type: "integer",
          minimum: 1000,
          maximum: 9999
        },
        questionId: { type: "string" },
        propSeq: { type: "number" },
        questionTitle: { type: "string" }, 
        propContent: { type: "string" },
        isTrue: { type: "boolean" },
        chapter: { type: "number" }
      },
      required: ["year", "questionId", "propSeq", "questionTitle", "propContent", "isTrue", "chapter"],
    },
  },
};

这样配置后,Middy的validator中间件会自动拦截不符合4位整数要求的年份请求,无需在baseHandler中额外编写验证逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 05:20:48