@aws-lambda-powertools/validation

中文文档
2.36.0发布于 2026/10/06MIT-0TypeScriptESM + CJS构建来源已验证近 30 天下载 1.5万

An utility to validate events and responses using JSON Schemas

原始使用文档
文档目录14 节
  1. Features
  2. Validator decorator
  3. Validator middleware
  4. Standalone validate function
  5. JMESPath support
  6. Extending the validator
  7. Contribute
  8. Roadmap
  9. Connect
  10. How to support Powertools for AWS Lambda (TypeScript)?
  11. Becoming a reference customer
  12. Sharing your work
  13. Using Lambda Layer
  14. License

Powertools for AWS Lambda (TypeScript) - Validation Utility

This utility provides JSON Schema validation for events and responses, including JMESPath support to unwrap events before validation.

Powertools for AWS Lambda (TypeScript) is a developer toolkit to implement Serverless best practices and increase developer velocity. You can use the library in both TypeScript and JavaScript code bases.

To get started, install the package by running:

npm i @aws-lambda-powertools/validation

Features

You can validate inbound and outbound payloads using the @validator class method decorator or validator Middy.js middleware.

You can also use the standalone validate function, if you want more control over the validation process such as handling a validation error.

Validator decorator

The @validator decorator is a TypeScript class method decorator that you can use to validate both the incoming event and the response payload.

If the validation fails, we will throw a SchemaValidationError.

import { validator } from '@aws-lambda-powertools/validation/decorator';
import type { Context } from 'aws-lambda';

const inboundSchema = {
  type: 'object',
  properties: {
    value: { type: 'number' },
  },
  required: ['value'],
  additionalProperties: false,
};

const outboundSchema = {
  type: 'object',
  properties: {
    result: { type: 'number' },
  },
  required: ['result'],
  additionalProperties: false,
};

class Lambda {
  @validator({
    inboundSchema,
    outboundSchema,
  })
  async handler(event: { value: number }, _context: Context) {
    // Your handler logic here
    return { result: event.value * 2 };
  }
}

const lambda = new Lambda();
export const handler = lambda.handler.bind(lambda);

It's not mandatory to validate both the inbound and outbound payloads. You can either use one, the other, or both.

Validator middleware

If you are using Middy.js, you can instead use the validator middleware to validate the incoming event and response payload.

import { validator } from '@aws-lambda-powertools/validation/middleware';
import middy from '@middy/core';

const inboundSchema = {
  type: 'object',
  properties: {
    foo: { type: 'string' },
  },
  required: ['foo'],
  additionalProperties: false,
};

const outboundSchema = {
  type: 'object',
  properties: {
    bar: { type: 'number' },
  },
  required: ['bar'],
  additionalProperties: false,
};

export const handler = middy()
  .use(validation({ inboundSchema, outboundSchema }))
  .handler(async (event) => {
    // Your handler logic here
    return { bar: 42 };
  });

Like the @validator decorator, you can choose to validate only the inbound or outbound payload.

Standalone validate function

The validate function gives you more control over the validation process, and is typically used within the Lambda handler, or any other function that needs to validate data.

When using the standalone function, you can gracefully handle schema validation errors by catching SchemaValidationError errors.

import { validate } from '@aws-lambda-powertools/validation';
import { SchemaValidationError } from '@aws-lambda-powertools/validation/errors';

const schema = {
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'number' },
  },
  required: ['name', 'age'],
  additionalProperties: false,
} as const;

const payload = { name: 'John', age: 30 };

export const handler = async (event: unknown) => {
  try {
    const validatedData = validate({
      payload,
      schema,
    });

    // Your handler logic here
  } catch (error) {
    if (error instanceof SchemaValidationError) {
      // Handle the validation error
      return {
        statusCode: 400,
        body: JSON.stringify({ message: error.message }),
      };
    }
    // Handle other errors
    throw error;
  }
}

JMESPath support

In some cases you might want to validate only a portion of the event payload - this is what the envelope option is for.

You can use JMESPath expressions to specify the path to the property you want to validate. The validator will unwrap the event before validating it.

import { validate } from '@aws-lambda-powertools/validation';

const schema = {
  type: 'object',
  properties: {
    user: { type: 'string' },
  },
  required: ['user'],
  additionalProperties: false,
} as const;

const payload = {
  data: {
    user: 'Alice',
  },
};

const validatedData = validate({
  payload,
  schema,
  envelope: 'data',
});

Extending the validator

Since the validator is built on top of Ajv, you can extend it with custom formats and external schemas, as well as bringing your own ajv instance.

The example below shows how to pass additional options to the validate function, but you can also pass them to the @validator decorator and validator middleware.

import { validate } from '@aws-lambda-powertools/validation';

const formats = {
  ageRange: (value: number) => return value >= 0 && value <= 120,
};

const definitionSchema = {
  $id: 'https://example.com/schemas/definitions.json',
  definitions: {
    user: {
      type: 'object',
      properties: {
        name: { type: 'string' },
        age: { type: 'number', format: 'ageRange' },
      },
      required: ['name', 'age'],
      additionalProperties: false,
    }
  }
} as const;

const schema = {
  $id: 'https://example.com/schemas/user.json',
  type: 'object',
  properties: {
    user: { $ref: 'definitions.json#/definitions/user' },
  },
  required: ['user'],
  additionalProperties: false,
} as const;

const payload = {
  user: {
    name: 'Alice',
    age: 25,
  },
};

const validatedData = validate({
  payload,
  schema,
  externalRefs: [definitionSchema],
  formats,
});

For more information on how to use the validate function, please refer to the documentation.

Contribute

If you are interested in contributing to this project, please refer to our Contributing Guidelines.

Roadmap

The roadmap of Powertools for AWS Lambda (TypeScript) is driven by customers’ demand.
Help us prioritize upcoming functionalities or utilities by upvoting existing RFCs and feature requests, or creating new ones, in this GitHub repository.

Connect

How to support Powertools for AWS Lambda (TypeScript)?

Becoming a reference customer

Knowing which companies are using this library is important to help prioritize the project internally. If your company is using Powertools for AWS Lambda (TypeScript), you can request to have your name and logo added to the README file by raising a Support Powertools for AWS Lambda (TypeScript) (become a reference) issue.

The following companies, among others, use Powertools:

Sharing your work

Share what you did with Powertools for AWS Lambda (TypeScript) 💞💞. Blog post, workshops, presentation, sample apps and others. Check out what the community has already shared about Powertools for AWS Lambda (TypeScript).

Using Lambda Layer

This helps us understand who uses Powertools for AWS Lambda (TypeScript) in a non-intrusive way, and helps us gain future investments for other Powertools for AWS Lambda languages. When using Layers, you can add Powertools as a dev dependency to not impact the development process.

License

This library is licensed under the MIT-0 License. See the LICENSE file.

版本与发布记录

@aws-lambda-powertools/validation 共发布 30 个版本,首次发布于 2025/03/13;过去 12 个月发布了 11 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.36.0latest2026/10/061 个月前
2.35.02026/08/182 个月前
2.34.02026/07/103 个月前
2.33.12026/05/255 个月前
2.33.02026/04/146 个月前
2.32.02026/03/197 个月前

其他发布通道:pre → 0.0.0。

关于 @aws-lambda-powertools/validation 的常见问题

@aws-lambda-powertools/validation 是什么?

An utility to validate events and responses using JSON Schemas

如何安装 @aws-lambda-powertools/validation?

在项目目录运行 npm install @aws-lambda-powertools/validation,或使用 pnpm add / yarn add / bun add。

@aws-lambda-powertools/validation 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aws-lambda-powertools/validation 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@aws-lambda-powertools/validation 可以商用吗?

@aws-lambda-powertools/validation 使用 MIT-0 许可。声明的许可为 MIT-0,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@aws-lambda-powertools/validation 的下载量有多少?

根据 npm 官方下载统计,@aws-lambda-powertools/validation 在 2026/10/08 – 2026/11/06 这 30 天内被下载 14,700 次,日均约 490 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aws-lambda-powertools/validation 还在维护吗?

最新版本 2.36.0 发布于 2026/10/06(1 个月前);至今共发布 30 个版本,其中过去 12 个月发布了 11 个;首次发布于 2025/03/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。