NestJS:如何在自定义验证器中访问 Body 和 Param

typescriptJS

1个回答

写回答

时空

2025-08-19 04:11

+ 关注

JS
JS

使用NestJS构建应用程序时,我们经常需要对请求进行验证。NestJS提供了一种方便的方式来自定义验证器,以确保输入数据的准确性。在这篇文章中,我们将探讨如何在自定义验证器中访问请求的Body和Param参数,并提供一些实际的案例代码。

什么是自定义验证器?

在NestJS中,验证器是一种用于验证输入数据的机制。默认情况下,NestJS提供了一些内置的验证器,例如验证字符串是否为空、验证电子邮件格式等。但是,有时候我们需要更复杂的验证逻辑,这就需要使用自定义验证器了。

如何创建自定义验证器?

首先,我们需要创建一个类来定义自定义验证器。这个类需要实现NestJSValidatorConstrAIntInterface接口,并实现其中的validate方法。在validate方法中,我们可以编写我们的自定义验证逻辑。下面是一个简单的例子:

typescript

import { ValidatorConstrAInt, ValidatorConstrAIntInterface, ValidationArguments } from 'class-validator';

@ValidatorConstrAInt({ name: 'custom', async: false })

export class CustomValidator implements ValidatorConstrAIntInterface {

validate(value: any, args: ValidationArguments) {

// 在这里编写自定义验证逻辑

return true; // 返回true表示验证通过,返回false表示验证失败

}

}

在上面的例子中,我们创建了一个名为CustomValidator的自定义验证器。这个验证器使用了class-validator库提供的装饰器@ValidatorConstrAInt,并实现了ValidatorConstrAIntInterface接口。在validate方法中,我们可以编写我们的自定义验证逻辑。

如何在自定义验证器中访问Body和Param?

有时候我们需要在自定义验证器中访问请求的Body和Param参数。为了实现这个目的,我们可以在创建自定义验证器的时候,将请求对象作为参数传递进去。下面是一个例子:

typescript

import { ValidatorConstrAInt, ValidatorConstrAIntInterface, ValidationArguments, ValidationOptions, registerDecorator } from 'class-validator';

import { Request } from 'express';

@ValidatorConstrAInt({ name: 'customWithRequest', async: false })

export class CustomValidatorWithRequest implements ValidatorConstrAIntInterface {

validate(value: any, args: ValidationArguments) {

const request: Request = args.object['request']; // 获取请求对象

const bodyParam = request.body.param; // 获取Body参数

const queryParam = request.query.param; // 获取QueryParam参数

// 在这里编写自定义验证逻辑

return true; // 返回true表示验证通过,返回false表示验证失败

}

}

export function CustomValidation(validationOptions?: ValidationOptions) {

return function (object: Object, propertyName: string) {

registerDecorator({

name: 'customValidation',

target: object.constructor,

propertyName: propertyName,

options: validationOptions,

validator: CustomValidatorWithRequest,

async: false,

});

};

}

在上面的例子中,我们创建了一个名为CustomValidatorWithRequest的自定义验证器。在validate方法中,我们可以通过args.object['request']来获取请求对象。然后,我们可以使用请求对象的body属性和query属性来访问Body和QueryParam参数。

案例代码

下面是一个使用自定义验证器的例子,我们创建了一个UserDto类,它包含了一个名为username的属性,我们对这个属性进行了自定义验证:

typescript

import { IsNotEmpty } from 'class-validator';

import { CustomValidation } from './custom-validator';

export class UserDto {

@IsNotEmpty()

@CustomValidation()

username: string;

}

在上面的例子中,我们使用@IsNotEmpty装饰器来验证username属性是否为空,并使用@CustomValidation装饰器来应用我们的自定义验证器。

这是一个简单的例子,演示了如何在自定义验证器中访问请求的Body和Param参数。希望通过这个例子能对你理解NestJS中的自定义验证器有所帮助。

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号