【问题标题】:Adding validation for required params in nestjs using class-validator使用 class-validator 在 nestjs 中为所需参数添加验证
【发布时间】:2019-11-30 21:32:23
【问题描述】:

使用类验证器,验证管道我想根据需要标记一些字段。我尝试使用@IsNotEmpty 方法。当输入为空时,它会抛出 400 错误。但是如果输入也丢失了,我也需要抛出一个错误。

DTO:地址对象,字段为地址 1 和地址 2。我希望地址 1 为必需,地址 2 为可选

import {IsString, IsInt, IsNotEmpty } from 'class-validator';
import {ApiModelProperty} from '@nestjs/swagger';
export class Address {

    @ApiModelProperty({description: 'Address Line 1', required : true})
    @IsString()
    @IsNotEmpty()
    required : true
    address1: string;

    @ApiModelProperty({description: 'Address Line 2', required :false})
    @IsString()
    address2?: string;
}
// App.js: Application file where validation pipes are defined.
async function bootstrap() {
    const expressServer = express();

    const app = await NestFactory.create(AppModule, expressServer, {bodyParser: true});
    app.use(bodyParser.json({limit: 6851000}));

    app.useGlobalInterceptors(new UnhandledExceptionInterceptor());

    app.useGlobalFilters(new HttpErrorsExceptionFilter());

    app.useGlobalFilters(new UnhandledExceptionFilter(newLogger('UnhandledExceptionFilter')));

    app.useGlobalPipes(new ValidationPipe({skipMissingProperties: true}));

    app.useGlobalPipes(new ValidationPipe({forbidNonWhitelisted :true, whitelist:true, transform:true}));

}

示例输入:包含两个字段的示例输入。

{  
  "shippingAddress": {
    "address1":,
    "address2": null 
  }
}

在这种情况下,这提供了预期的 400,但是当输入如下所示缺少必填字段之一时,我也需要一个错误,

{  
  "shippingAddress": {
    "address2": null
   } 
}

【问题讨论】:

    标签: nestjs class-validator


    【解决方案1】:

    这是class-validator 的标准功能,只要您不添加@IsOptional() 装饰器。我将管道直接添加到控制器,但想法是一样的。在下面查看我的课程和标注:

    // test-class.ts
    import { IsString, IsOptional } from 'class-validator';
    
    export class TestClass {
      @IsString()
      address1: string;
    
      @IsString()
      @IsOptional()
      address2?: string;
    }
    
    //test-valid.controller.ts
    import { Controller, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common';
    import { TestClass } from './models/test-class';
    
    @Controller('test-valid')
    export class TestValidController {
    
      @Post()
      @UsePipes(new ValidationPipe({skipMissingProperties: true}))
      @UsePipes(new ValidationPipe({forbidNonWhitelisted: true, whitelist: true, transform: true}))
      async testValidate(@Body() body: TestClass) {
        return 'Valid!';
      }
    }
    
    
    # cURL callouts 
    ~/Documents/gitRepos/nest-testing
    $ curl -X POST http://localhost:3000/test-valid \
    > --header "Content-Type: application/json" \
    > --data '{"address1": "some address", "address2": "some other address"}'
    Valid!
    
    ~/Documents/gitRepos/nest-testing
    $ curl -X POST http://localhost:3000/test-valid --header "Content-Type: a
    pplication/json" --data '{"address2": "some other address"}'
    [{"target":{"address2":"some other address"},"property":"address1","children":[],"constraints":{"isString":"address1 must be a string"}}]
    
    ~/Documents/gitRepos/nest-testing
    $ curl -X POST http://localhost:3000/test-valid --header "Content-Type: a
    pplication/json" --data '{"address1": "some address"}'
    Valid!
    

    可以查看address1是否缺失class-validator会抛出错误。

    查看您的代码,您的required: true 就在您的address1: string 上方,而不是在装饰器中,这可能会导致将装饰器应用于字段required 而不是address1 的问题,只是一些我想我会指出来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-09
      • 2020-02-09
      • 2022-01-19
      • 2014-08-05
      • 2020-11-29
      • 2019-08-29
      • 2020-08-07
      • 1970-01-01
      相关资源
      最近更新 更多