首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用class-validator为nestjs中的必需参数添加验证

使用class-validator为nestjs中的必需参数添加验证
EN

Stack Overflow用户
提问于 2019-07-23 05:25:12
回答 1查看 5.6K关注 0票数 0

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

DTO:具有字段address1和Address 2的address对象。我希望address1为必填,address2为可选

代码语言:javascript
复制
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;
}
代码语言:javascript
复制
// 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}));

}

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

代码语言:javascript
复制
{  
  "shippingAddress": {
    "address1":,
    "address2": null 
  }
}

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

代码语言:javascript
复制
{  
  "shippingAddress": {
    "address2": null
   } 
}
EN

回答 1

Stack Overflow用户

发布于 2019-07-24 00:52:09

只要不添加@IsOptional()装饰器,这就是class-validator的标准功能。我将管道直接添加到控制器中,但想法是相同的。请参阅下面的类和标注:

代码语言:javascript
复制
// test-class.ts
import { IsString, IsOptional } from 'class-validator';

export class TestClass {
  @IsString()
  address1: string;

  @IsString()
  @IsOptional()
  address2?: string;
}
代码语言:javascript
复制
//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!';
  }
}
代码语言:javascript
复制
# 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,这是我想指出的问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57153948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档