简体   繁体   English

Nestjs自定义类验证器装饰器没有从参数中获取值

[英]Nestjs custom class-validator decorator doesn't get the value from param

I have created a Custom ValidatorConstraint in Nestjs from class-validator, just to create my own decorator and apply later to DTO classes for validations.我从 class-validator 在 Nestjs 中创建了一个自定义 ValidatorConstraint,只是为了创建我自己的装饰器并稍后应用于 DTO 类进行验证。

Imagine this route.想象一下这条路线。

foo/:client foo/:客户端

after request it, I just want to check that client contains some pattern请求后,我只想检查客户端是否包含一些模式

client --> XXX123 ✘客户端 --> XXX123 ✘

client --> ZZZ123 ✔客户端 --> ZZZ123 ✔

I am struggling with it and although I saw some examples, it is still not very clear why it fails.我正在努力解决它,虽然我看到了一些例子,但仍然不太清楚它为什么会失败。

main.ts main.ts

app.useGlobalPipes(new ValidationPipe());
useContainer(app.select(AppModule), { fallbackOnErrors: true });

app.module.ts app.module.ts

providers: [..., IsValidClientConstraint],

app.controller.ts应用程序控制器.ts

  @Get(':client')
  getHello(@Param('client') client: ClientDTO): string {

custom.validator.ts custom.validator.ts

import { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';
import { Injectable } from '@nestjs/common';

@ValidatorConstraint({ async: false })
@Injectable()
export class IsValidClientConstraint implements ValidatorConstraintInterface {
  validate(client: any, args: ValidationArguments) {
    console.log(client)
    return client.includes('ZZZ');
  }
}

export function IsValidClient(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsValidClientConstraint,
    });
  };
}

client.dto.ts客户端.dto.ts

export class ClientDTO {


  @IsValidClient({ message: 'blabla' })
  client: string;

}

However doing a request with -> foo/XXX344但是使用 -> foo/XXX344 发出请求

ERROR [ExceptionsHandler] Cannot read properties of undefined错误 [ExceptionsHandler] 无法读取未定义的属性

So it is not receiving the value of the client itself所以它没有收到客户本身的价值

What am I missing there?我在那里想念什么?

I with leave the repo here我把回购留在这里

https://github.com/ackuser/nestjs-sample-custom-validator https://github.com/ackuser/nestjs-sample-custom-validator

Thanks,谢谢,

I appreciate any help我很感激任何帮助

You don't have to pass parameter name to @Param decorator when you want to use class-validator to validate params, So change it to @Param() params: ClientDTO instead.当您想使用class-validator来验证参数时,您不必将参数名称传递给@Param装饰器,因此请将其更改为@Param() params: ClientDTO

Use custom pipes if you want to validate each parameter one by one.如果要逐个验证每个参数,请使用自定义管道 because the DTO method you used turns all parameters (not just :client ) into a single data class.因为您使用的 DTO 方法将所有参数(不仅仅是:client )转换为单个数据类。

Also in IsValidClientConstraint check if client is defined before using it.同样在IsValidClientConstraint检查client是否在使用之前定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM