标签: class-validator

通过 @IsInt() 验证 application/x-www-form-urlencoded 请求类型

当我浏览Pipes文档时,我注意到我无法正确@IsInt()验证application/x-www-form-urlencoded请求,导致我通过的所有值都作为字符串值接收。

我的请求数据如下所示 在此处输入图片说明

我的 DTO 看起来像

import { IsString, IsInt } from 'class-validator';

export class CreateCatDto {
    @IsString()
    readonly name: string;

    @IsInt()
    readonly age: number;

    @IsString()
    readonly breed: string;
}
Run Code Online (Sandbox Code Playgroud)

验证管道包含下一个代码

import { PipeTransform, Pipe, ArgumentMetadata, BadRequestException } from '@nestjs/common';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';

@Pipe()
export class ValidationPipe implements PipeTransform<any> {
    async transform(value, metadata: ArgumentMetadata) {
        const { metatype } = metadata;
        if (!metatype || !this.toValidate(metatype)) { …
Run Code Online (Sandbox Code Playgroud)

node.js class-validator nestjs class-transformer

3
推荐指数
2
解决办法
2041
查看次数

DTO 不适用于微服务,而是直接适用于 api

我正在 NestJS 中开发 api 和微服务,这是我的控制器功能

    @Post()
    @MessagePattern({ service: TRANSACTION_SERVICE, msg: 'create' })
    create( @Body() createTransactionDto: TransactionDto_create ) : Promise<Transaction>{
        return this.transactionsService.create(createTransactionDto)
    }
Run Code Online (Sandbox Code Playgroud)

当我调用 post api 时,dto 验证工作正常,但是当我使用微服务调用此验证时,验证不起作用,它会传递到服务而不会因错误而拒绝。这是我的 DTO

import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
export class TransactionDto_create{
    @IsNotEmpty()
    action: string;

    // @IsString()
    readonly rec_id : string;

    @IsNotEmpty()
    readonly data : Object;

    extras : Object;
    // readonly extras2 : Object;
}
Run Code Online (Sandbox Code Playgroud)

当我调用没有操作参数的 api 时,它会显示所需的错误操作,但是当我使用微服务调用它时

const 模式 = { 服务: TRANSACTION_SERVICE, msg: '创建' }; const data = {id: '5d1de5d787db5151903c80b9', extras:{'asdf':'dsf'}}; …

microservices class-validator nestjs

3
推荐指数
1
解决办法
5844
查看次数

如何从 NestJS 中的类验证器返回自定义响应

是否可以从 NestJs 内部的类验证器返回自定义错误响应。

NestJS 当前返回如下错误消息:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": [
        {
            "target": {},
            "property": "username",
            "children": [],
            "constraints": {
                "maxLength": "username must be shorter than or equal to 20 characters",
                "minLength": "username must be longer than or equal to 4 characters",
                "isString": "username must be a string"
            }
        },
    ]
}
Run Code Online (Sandbox Code Playgroud)

然而,使用我的 API 的服务需要更类似于:

{
    "status": 400,
    "message": "Bad Request",
    "success": false,
    "meta": {
        "details": {
            "maxLength": "username must be shorter than or equal to 20 characters", …
Run Code Online (Sandbox Code Playgroud)

javascript typescript class-validator nestjs

3
推荐指数
1
解决办法
6604
查看次数

尽管要求应该通过,但数字参数验证失败

我想通过坐标获取位置。我从一个简单的 DTO 开始

export class GetLocationByCoordinatesDTO {
    @IsNumber()
    @Min(-90)
    @Max(90)
    public latitude: number;

    @IsNumber()
    @Min(-180)
    @Max(180)
    public longitude: number;
}
Run Code Online (Sandbox Code Playgroud)

和这个 API 端点

@Get(':latitude/:longitude')
public getLocationByCoordinates(@Param() { latitude, longitude }: GetLocationByCoordinatesDTO): Promise<Location> {
  // ...
}
Run Code Online (Sandbox Code Playgroud)

为了测试这个端点,我调用这个 url

本地主机:3000/位置/0/0

不幸的是我得到了以下回复

{
    "statusCode": 400,
    "message": [
        "latitude must not be greater than 90",
        "latitude must not be less than -90",
        "latitude must be a number conforming to the specified constraints",
        "longitude must not be greater than 180",
        "longitude must not be …
Run Code Online (Sandbox Code Playgroud)

typescript class-validator nestjs

3
推荐指数
1
解决办法
3638
查看次数

如何在 Nestjs 验证中将异常错误作为对象获取?

默认情况下,当验证失败时,响应结果如下

{
    statusCode: 400,
    message: [ 'Provide a url.', 'test must be a string' ],
    error: 'Bad Request'
}
Run Code Online (Sandbox Code Playgroud)

如何获取消息的值:

{
    statusCode: 400,
    message: {
        "url": 'Provide a url.',
        "test": 'test must be a string'
    },
    error: 'Bad Request'
}
Run Code Online (Sandbox Code Playgroud)

javascript node.js class-validator nestjs

3
推荐指数
1
解决办法
4215
查看次数

MongoDB 和类验证器唯一验证 - NESTJS

长话短说

我正在尝试在我的验证器中运行猫鼬查询


您好,我正在尝试制作一个自定义装饰器,如果该字段的值已存在,它会抛出错误。我正在尝试在验证路线的类中使用猫鼬模型。与解析器/控制器不同,它@InjectModel()在验证器类中不起作用。我的验证器是这样的

import { getModelToken, InjectModel } from "@nestjs/mongoose";
import {
  ValidationArguments,
  ValidatorConstraint,
  ValidatorConstraintInterface,
} from "class-validator";
import { Model } from "mongoose";
import { User } from "../schema/user.schema";

@ValidatorConstraint({ name: "IsUniqueUser", async: true })
export class UniqueValidator implements ValidatorConstraintInterface {
  constructor(
    @InjectModel(User.name)
    private readonly userModel: Model<User>,
  ) {}

  async validate(value: any, args: ValidationArguments) {
    const filter = {};

    console.log(this.userModel);
    console.log(getModelToken(User.name));
    filter[args.property] = value;
    const count = await this.userModel.count(filter);
    return !count;
  }

  defaultMessage(args: ValidationArguments) {
    return "$(value) …
Run Code Online (Sandbox Code Playgroud)

javascript mongoose typescript class-validator nestjs

3
推荐指数
1
解决办法
5114
查看次数

类验证器:根据另一个属性的值在验证时删除一个属性

与 NestJS 一起使用class-validator,我的工作如下:

export class MatchDeclineReason {
  @IsString()
  @IsEnum(MatchDeclineReasonType)
  @ApiProperty()
  type: MatchDeclineReasonType;

  @ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
  @IsString()
  @ApiProperty()
  freeText: string;
}
Run Code Online (Sandbox Code Playgroud)

所以如果delinceReason.type === Other,我希望得到一个freeText字符串值。


但是,如果 与declineReason.type有任何不同Other,我希望该freeText财产被剥夺。

有没有什么方法可以在不编写 的情况下实现这种行为CustomValidator

我的ValidationPipe配置:

  app.useGlobalPipes(
    new ValidationPipe({
      disableErrorMessages: false,
      whitelist: true,
      transform: true,
    }),
  );
Run Code Online (Sandbox Code Playgroud)

validation typescript class-validator nestjs

3
推荐指数
1
解决办法
5616
查看次数

@Transform() 布尔转换在 DTO 上不起作用

我在 DTO 中使用 NestJS 和类转换器。

这是我所做的和我的问题的一个简单示例:

    export class SomeDTO{
        @Transform(({ value }) => value === "true" || value === true || value === 1)
        @IsBoolean()
        doDelete : boolean;
    }
Run Code Online (Sandbox Code Playgroud)

我什至尝试过@Transform(({ value }) => { return value === "true" || value === true || value === 1})

现在,在我的控制器中:

@Post("something")
someOperation(@Body()  data : SomeDTO){
    console.log(data); 
}
Run Code Online (Sandbox Code Playgroud)

记录数据时,预期的布尔值doDelete仍然是字符串,并且没有转换为其本机布尔类型。

是否尝试过提供这样的数据: @Transform(({ value }) => { return false})

但在控制器中,如果我们将原始DTO doDelete设置为true,数据仍然是相同的。它没有像我们通过 暗示的那样转换为 false @Transform()

我做错什么了吗?感谢您的帮助并提供了一些线索。

我已经尝试过这些相关参考文献,但似乎没有任何效果。

typescript class-validator nestjs class-transformer

3
推荐指数
1
解决办法
3566
查看次数

如何使用类验证器验证 URL 数组?

我正在使用 Class-Validator 来验证 Nest.js 应用程序的 DTO 属性。在那里我有一个属性“images”,它是一个字符串数组,这些字符串是 URL。因此,我想验证该数组中的每个 URL。


class SomeDto {
// ...
       
// Array of Urls
@IsArray()
@IsUrl({each:true})
images: string[];

// ...
}
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用。有谁知道如何验证这个 URL 数组。

dto typescript class-validator nestjs

3
推荐指数
1
解决办法
1876
查看次数

使用类验证器在 Nest js 中自定义错误消息

我正在开发一个 Nest 项目,并使用类验证器进行验证。

目前,如果存在任何验证错误,我收到的错误响应为

{
    "statusCode": 400,
    "message": [
        "Title is too long. Maximal length is 50 characters, but actual is $value",
        "Title is too short. Minimal length is 10 characters, but actual is $value"
    ],
    "error": "Bad Request"
}
Run Code Online (Sandbox Code Playgroud)

但是我们可以将消息作为对象数组,而不是字符串数组。因此,FE 可以轻松找出哪个字段出现错误,例如

{
    "message": [
        { "field": "title", "error": "Title is too long. Maximal length is 50 characters, but actual is $value" },
        { "field": "title", "error": "Title is too short. Minimal length is 10 characters, but actual is $value" …
Run Code Online (Sandbox Code Playgroud)

validation class-validator nestjs

3
推荐指数
1
解决办法
6832
查看次数