使用类验证器,验证管道,我想标记一些需要的字段。我尝试使用@IsNotEmpty方法。当输入为空时,它会抛出一个400错误。但是如果输入也丢失了,我需要抛出一个错误。
DTO:具有字段address1和Address 2的address对象。我希望address1为必填,address2为可选
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
}
}发布于 2019-07-24 00:52:09
只要不添加@IsOptional()装饰器,这就是class-validator的标准功能。我将管道直接添加到控制器中,但想法是相同的。请参阅下面的类和标注:
// 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,这是我想指出的问题。
https://stackoverflow.com/questions/57153948
复制相似问题